To briefly explain, I have two components with content that should be updated on window resize. On every window resize we do a history.replace() to a new url and a history.push() back to the old url so that there's a real simulation of change of url. I have created three different situations.
The third scenario is what I'm particular about. I need a way to always update class component after it mounts. Just as it happens for the two above.
I'm trying to wrap my head around what really causes this behavior.
I've written a sample sandbox code to produce what I'm experiencing.
You're mapping your Redux state to props
already with mapStateToProps
so you don't need to set it in the component's local state
with componentDidMount
. Just use this.props.dim
in your render
method:
{this.props.dim.mobi} => {this.props.dim.editButtonBottom}
I want to be able to change the values in the component after every mount. I don't want to always depend on the values from the global state.
If you'd like to be able to display a value based on props
but have the option of overriding that value with state
then you can do something like this:
returnStyleBottom = () => {
return this.state.style.bottom || this.props.dim.editButtonBottom;
}
render() {
return (
...
<p>
Bad (now nice): {this.state.dim.mobi} => {this.returnStyleBottom()}
</p>
);
}
I've updated your sandbox with this code so you can test it out: https://codesandbox.io/s/lrryn9nl09
By default you have this.state.style.bottom
set to 0
so the value of this.props.dim.editButtonBottom
will be used. If you update this.state.style.bottom
then that will become the displayed value. And if you want to go back to using the value from props
just set the state
value back to 0
.
Problem solved by adding a componentDidUpdate and comparing props.
Even though this is not so recommended as something like this should only be used in rare cases, this is the only thing that seems to produce the result I was looking for!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.