I use this to method to work with component, the componentWillMount to initialize data for homepage and the componentWillReceiveProps when router change (category page), but when I come back home page from category page, I know because componentWillMount just do one time so I cannot see data.
componentWillMount(){
this.props.fetchBooks(1)
}
componentWillReceiveProps(nextProps){
if(nextProps.match.params.id && nextProps.match.params.id !== this.props.match.params.id){
this.props.fetchBookByCategory(nextProps.match.params.id)
}
}
I put this initialized code to componentWillReceiveProps, It works but It calls the fetchBooks(1) constantly eventhough I tried to do with some condition, please help me this problems, many thanks.
You have to set nextProps to this.props on componentWillReceiveProps
componentWillReceiveProps(nextProps){
if(nextProps.match.params.id && nextProps.match.params.id !== this.props.match.params.id){
this.props.fetchBookByCategory(nextProps.match.params.id)
this.props = nextProps;
}
Never do fetching in componentWillMount
or the constructor
. instead do it in componentDidMount
.
componentWillMount() is invoked immediately before mounting occurs. It is called before render(), therefore setting state synchronously in this method will not trigger a re-rendering. Avoid introducing any side-effects or subscriptions in this method.
componentDidMount() is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request. Setting state in this method will trigger a re-rendering.
You can conditionally render your page if data wasn't received yet.
render(){
return(
<div>
{
data.length > 0 ?
<List items={data} /> :
<div>Loading...</div>
}
</div>
);
}
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.