3 ms·
> when you can just have real functions doing setState() updates on the relevant component Using Redux, all or almost all of your state is stored in a global r
by ht85 10y ago
> when you can just have real functions doing setState() updates on the relevant component
Using Redux, all or almost all of your state is stored in a global repository (the "store").
Those strings should probably be constants instead, especially for IDE auto-complete purpose, but you are never generating those manually.
Instead, your components would call "action creators", who are properly named functions, which in turn will dispatch one or several actions to the store.
In your component:
actions.changeLocation(someLocation)
In your action creator:
changeLocation(location) {
dispatch({
type: CONSTANTS.CHANGE_LOCATION,
payload: { location },
});
}
- hamandcheese 10y agoIs it acceptable to dispatch inside your action creators? I'm somewhat new to redux but I got the impression that dispatch should be used inside mapDispatchToProps.
- yawgmoth 10y agoIt's an example of the thunk pattern. Thunks are used when you have an async call, e.g. getFoos. Then your action creator would be function requestFoos() { return { type: REQ_FOOS } } function gotFoos(foos) { return { type: GOT_FOOS, foos } } export function getFoos() { return function(dispatch) { dispatch(requestFoos()); myFooProvider .getFoos() .then(function(foos) { dispatch(gotFoos(foos)); }); } } Really useful for writing reducers that want to keep track of when you're fetching data from the server.
- hamandcheese 10y agoYes, but in the parent comment a thunk wasn't being dispatched, but rather a closure around some unknown dispatch function is being called.
- sixo 10y agoI found that redux only made sense once I started using redux-thunk to dispatch and handle quite a bit of logic inside the action-creators.
- hamandcheese 10y agoMy question was because if you look closely it isn't actually a thunk.