问题
I have a problem with Redux, even more likely not a problem but a misunderstanding. If I do dispatch in a function and write a new value in the store then I can not immediately get into this function a new value from the store.
Example:
testFunc = () => {
console.log('in func: before', this.props.count); //state store
this.props.onButtonIncrementClick(); //dispatch a new state in the store
console.log('in func: after', this.props.count); //get the old state store
};
Live example: https://codesandbox.io/s/yk1jzjv6l1
I suspect this is related to asynchrony since if I wrap the state in setTimeout() a new state comes.
I would be glad to hear an explanation of why and how you can write values to the store and immediately read them from it.
回答1:
setState is not synchronous, whether it's you or Redux updating it.
This is a misunderstanding, as you say. When you're updating it directly you may supply a callback to be executed, e.g.,
setState({ foo }, () => somethingWith(this.state));
(Noting that the component has been re-rendered before the callback.)
If you have logic you need to run after an "external" state update (e.g., Redux) then there's componentDidUpdate, but it may also indicate an architectural issue.
回答2:
I do not know if it's a good pratice, but this works
onButtonIncrementClick: () => new Promise(resolve => {
dispatch({ type: 'INCREMENT' });
resolve()
})
...
this.props.onButtonIncrementClick().then(() => {
console.log('in func: after', this.props.count);
})
来源:https://stackoverflow.com/questions/51247040/redux-does-not-update-state-immediately