I have a little problem in my React/Redux application.
When I dispatch an action to change my redux state, React component receives the changed state asynchronously. But I want to handle the changes synchronously.
The code is here:
// Component
class App extends React.Component {
handleButtonChange = e => {
this.props.change("Hello World");
console.log(this.props.title); // print old value
setTimeout(() => {
console.log(this.props.title); // print new value
}, 100);
};
render() {
return (
<div className="App">
<button onClick={this.handleButtonChange}>
Change the title
</button>
</div>
);
}
}
const mapStateToProps = state => ({
title: state.title
});
const mapDispatchToProps = dispatch => ({
change: title => dispatch(change(title))
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(App);
Any ideas?
The full example is here: https://codesandbox.io/s/lxjkvvk3pl
The
connect()
method, it does not modify the component class passed to it; instead, it returns a new, connected component class for you to use.The
mapStateToProps()
function is called any time the connector component needs to compute new props, as a result of a store state change.Reference: react-redux api
When you dispatch an action:
Which will make the store state change, as a result, the
mapStateToProps()
function will be invoked and theconnect()
function will get the current component and return for you a new component with the updatedprops
.The
console.log(this.props.title)
is executed with the value of the property title of the old props object of the old component.I put some lifecycle hooks in your codes to see what actually happened:
And the results after clicking four times on the button are:
Therefore, in case you want to use the new computed props for the first time, it's updated, you should do it in the
componentDidUpdate()
However, I also see that you want to use the new
props
directly after dispatching an action:I think that's somehow impossible.
The rework demo: https://codesandbox.io/s/wol55qqx0k