Reputation: 5776
I have a react component that needs to do some computing on its WillReceiveProps state. This is what the component looks like:
import React from 'react'
import {connect} from 'react-redux'
import Message from './Message.react'
class MessageContainer extends React.Component {
constructor() {
super();
this.state = {show: false, message: null}
}
componentWillReceiveProps(nextProps, nextState) {
if (nextProps.message) {
this.setState({show: true});
setTimeout(
() => {
this.setState({show: false})
},
5000);
}
}
render() {
let message = this.props.message;
return (message ? <Message message={message} show={this.state.show}/> : null)
}
}
const mapStateToProps = (state,ownProps) => {
return {
message: state.message
}
};
export default connect(mapStateToProps, {})(MessageContainer);
The idea is that if a String prop called 'message' changes, then we should show the component and after 5 seconds we should hide it.
It work correctly except that if for some reason, the new message is the same value that the last (for instance "Item successfully added") componentWillReceiveProps is not being called, which means the component is not shown.
How do I handle this situation? I'm open to clear the props but I'm not sure where to do that.
Upvotes: 2
Views: 947
Reputation: 4779
Since you're connecting your component to redux with connect(), your exported component is actually a high order component which implements shouldComponentUpdate
(SCU) internally for you by react-redux binding. (similar to React.PureComponent
).
Your connected component only need to pass down single state prop state.message
(no dispatchProps and ownProps), as long as it remains unchanged, SCU returns false, your connected component will not rerender, thus your componentWillReceiveProps don't get called.
You can turn off the default optimization by passing a config object to the 4th parameter as follow and your componentWillReceiveProps should get called as you expected.
connect(
mapStateToProps,
null,
null,
{ pure: false }
)
Upvotes: 6