React Component Not Re-rendering When State Changes
Solution 1:
You probably want to use shouldComponentUpdate
instead, as what you want is to do stuff before the component is re-rendered.
Check this out: https://code.likeagirl.io/understanding-react-component-life-cycle-49bf4b8674de
and this: http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/
Solution 2:
You can really simplify this and make it cleaner, and this should also fix your problem:
In your render do:
return (
<div style={{backgroundImage:`url(${background})`,height:'100vh',overflowX:'hidden',backgroundSize:'cover'}}>
<Navbar/>
<InfoDisplay data={this.state.data} />
</div>
)
Then in your componentDidMount and componentDidUpdate all you have to do is set the state data to data.content from your request:
case 'legende': import('../data/legends.json').then((data) => {
this.setState({
data: data.content,
});
});
obviously you will need to change your constructor as well to be have data:
this.state = {data: null};
Hope this helps.
Solution 3:
componentDidUpdate() will be invoked if a re-rendering is complete => In fact like you said there is no re-rendering because you never invoke any setState Method.
I'm not very sure if a state can hold a JSX content.
Maybe try it like this:
this.setState({
element: data.content
})
==
<div style={{backgroundImage:`url(${background})`,height:'100vh',overflowX:'hidden',backgroundSize:'cover'}}>
<Navbar/><InfoDisplaydata={this.state.element} />
</div>
hope you find your bug with this information
Solution 4:
if you want to re-render on any update then you should use
componentWillReceiveProps(nextProps){
this.setState({element:nextProps.data})
}
Post a Comment for "React Component Not Re-rendering When State Changes"