Movatterモバイル変換


[0]ホーム

URL:


Skip to main content

Store

A store holds the wholestate tree of your application.The only way to change the state inside it is to dispatch anaction on it, which triggers theroot reducer function to calculate the new state.

A store is not a class. It's just an object with a few methods on it.

To create a store,pass your rootreducer function to Redux Toolkit'sconfigureStore method, which will set up a Redux store with a good default configuration. (Alternately, if you're not yet using Redux Toolkit, you can use the originalcreateStore method, but we encourage you tomigrate your code to use Redux Toolkit as soon as possible)

Store Methods

getState()

Returns the current state tree of your application.It is equal to the last value returned by the store's reducer.

Returns

(any): The current state tree of your application.


 

dispatch(action)

Dispatches an action. This is the only way to trigger a state change.

The store's reducer function will be called with the currentgetState() result and the givenaction synchronously. Its return value will be considered the next state. It will be returned fromgetState() from now on, and the change listeners will immediately be notified.

caution

If you attempt to calldispatch from inside thereducer, it will throw with an error saying "Reducers may not dispatch actions." Reducers are pure functions - they canonly return a new state value and must not have side effects (and dispatching is a side effect).

In Redux, subscriptions are called after the root reducer has returned the new state, so youmay dispatch in the subscription listeners. You are only disallowed to dispatch inside the reducers because they must have no side effects. If you want to cause a side effect in response to an action, the right place to do this is in the potentially asyncaction creator.

Arguments

  1. action (Object): A plain object describing the change that makes sense for your application. Actions are the only way to get data into the store, so any data, whether from the UI events, network callbacks, or other sources such as WebSockets needs to eventually be dispatched as actions. Actions must have atype field that indicates the type of action being performed. Types can be defined as constants and imported from another module. It's better to use strings fortype thanSymbols because strings are serializable. Other thantype, the structure of an action object is really up to you. If you're interested, check outFlux Standard Action for recommendations on how actions could be constructed.

Returns

(Object): The dispatched action (see notes).

Notes

The “vanilla” store implementation you get by callingcreateStore only supports plain object actions and hands them immediately to the reducer.

However, if you wrapcreateStore withapplyMiddleware, the middleware can interpret actions differently, and provide support for dispatchingasync actions. Async actions are usually asynchronous primitives like Promises, Observables, or thunks.

Middleware is created by the community and does not ship with Redux by default. You need to explicitly install packages likeredux-thunk orredux-promise to use it. You may also create your own middleware.

To learn how to describe asynchronous API calls, read the current state inside action creators, perform side effects, or chain them to execute in a sequence, see the examples forapplyMiddleware.

Example

import{ createStore}from'redux'
const store=createStore(todos,['Use Redux'])

functionaddTodo(text){
return{
type:'ADD_TODO',
text
}
}

store.dispatch(addTodo('Read the docs'))
store.dispatch(addTodo('Read about the middleware'))

 

subscribe(listener)

Adds a change listener. It will be called any time an action is dispatched, and some part of the state tree may potentially have changed. You may then callgetState() to read the current state tree inside the callback.

You may calldispatch() from a change listener, with the following caveats:

  1. The listener should only calldispatch() either in response to user actions or under specific conditions (e. g. dispatching an action when the store has a specific field). Callingdispatch() without any conditions is technically possible, however it leads to an infinite loop as everydispatch() call usually triggers the listener again.

  2. The subscriptions are snapshotted just before everydispatch() call. If you subscribe or unsubscribe while the listeners are being invoked, this will not have any effect on thedispatch() that is currently in progress. However, the nextdispatch() call, whether nested or not, will use a more recent snapshot of the subscription list.

  3. The listener should not expect to see all state changes, as the state might have been updated multiple times during a nesteddispatch() before the listener is called. It is, however, guaranteed that all subscribers registered before thedispatch() started will be called with the latest state by the time it exits.

It is a low-level API. Most likely, instead of using it directly, you'll use React (or other) bindings. If you commonly use the callback as a hook to react to state changes, you might want towrite a customobserveStore utility. TheStore is also anObservable, so you cansubscribe to changes with libraries likeRxJS.

To unsubscribe the change listener, invoke the function returned bysubscribe.

Arguments

  1. listener (Function): The callback to be invoked any time an action has been dispatched, and the state tree might have changed. You may callgetState() inside this callback to read the current state tree. It is reasonable to expect that the store's reducer is a pure function, so you may compare references to some deep path in the state tree to learn whether its value has changed.
Returns

(Function): A function that unsubscribes the change listener.

Example
functionselect(state){
return state.some.deep.property
}

let currentValue
functionhandleChange(){
let previousValue= currentValue
currentValue=select(store.getState())

if(previousValue!== currentValue){
console.log(
'Some deep nested property changed from',
previousValue,
'to',
currentValue
)
}
}

const unsubscribe= store.subscribe(handleChange)
unsubscribe()

 

replaceReducer(nextReducer)

Replaces the reducer currently used by the store to calculate the state.

It is an advanced API. You might need this if your app implements code splitting, and you want to load some of the reducers dynamically. You might also need this if you implement a hot reloading mechanism for Redux.

Arguments

  1. nextReducer (Function) The next reducer for the store to use.

[8]ページ先頭

©2009-2025 Movatter.jp