Answer the question
In order to leave comments, you need to log in
How to force a component update when setState() is called?
What a story, I use the following construction to display nested pages.
class Screen extends Componen {
constructor(props) {
super(props)
this.state = {
screen: undefined
}
}
render() {
return this.state.screen ? this.state.screen : <div className="content">
</div>
}
}
this.setState({screen: <MyMyComponenr/>})
this.setState({screen: undefined}, ()=>{
this.setState({
screen: <ShowScreen />
})
})
}}
Answer the question
In order to leave comments, you need to log in
this.setState({ screen: <Random key={Math.random()} /> });
What's happening. React understands that the same component needs to be rendered, so it doesn't re-render it. If you add the componentDidUpdate method, you will see that it is being called - React reuses the existing component instance.
The problem is that this is a so-so approach in React. In order, in my opinion, to write this example more concisely in the React way, we need to slightly correct the responsibility of each component.
https://codesandbox.io/s/2vl0801r6r
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question