Reactjs 反应生命周期
我使用这个方法来处理组件,组件将挂载以初始化主页的数据,当路由器更改(类别页面)时,组件将接收Props,但当我从类别页面返回主页时,我知道,因为组件挂载只执行一次,所以我看不到数据Reactjs 反应生命周期,reactjs,react-lifecycle,Reactjs,React Lifecycle,我使用这个方法来处理组件,组件将挂载以初始化主页的数据,当路由器更改(类别页面)时,组件将接收Props,但当我从类别页面返回主页时,我知道,因为组件挂载只执行一次,所以我看不到数据 componentWillMount(){ this.props.fetchBooks(1) } componentWillReceiveProps(nextProps){ if(nextProps.match.params.id && nextProps.m
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)
}
}
我将此初始化代码放入componentWillReceiveProps,它可以工作,但它会不断调用fetchBooks(1),即使我尝试处理某些条件,请帮助我解决此问题,非常感谢。您必须将下一步操作设置为此。componentWillReceiveProps上的props
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;
}
您必须将nextProps设置为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;
}
永远不要在
组件willmount
或构造函数中提取。而是在componentDidMount
中执行此操作
:
componentWillMount()在装入之前立即调用。信息技术
在render()之前调用,因此在中同步设置状态
此方法不会触发重新渲染。避免引入任何
此方法中的副作用或订阅
componentDidMount()在创建组件后立即调用
安装。需要DOM节点的初始化应该在这里进行。如果你
需要从远程端点加载数据,这是一个好地方
实例化网络请求。此方法中的设置状态将
触发重新渲染
如果尚未收到数据,则可以有条件地呈现页面
render(){
return(
<div>
{
data.length > 0 ?
<List items={data} /> :
<div>Loading...</div>
}
</div>
);
}
render(){
返回(
{
数据长度>0?
:
加载。。。
}
);
}
永远不要提取组件将装入或构造函数。而是在componentDidMount
中执行此操作
:
componentWillMount()在装入之前立即调用。信息技术
在render()之前调用,因此在中同步设置状态
此方法不会触发重新渲染。避免引入任何
此方法中的副作用或订阅
componentDidMount()在创建组件后立即调用
安装。需要DOM节点的初始化应该在这里进行。如果你
需要从远程端点加载数据,这是一个好地方
实例化网络请求。此方法中的设置状态将
触发重新渲染
如果尚未收到数据,则可以有条件地呈现页面
render(){
return(
<div>
{
data.length > 0 ?
<List items={data} /> :
<div>Loading...</div>
}
</div>
);
}
render(){
返回(
{
数据长度>0?
:
加载。。。
}
);
}
谢谢!,使用我发布的代码,componentDidMount和WillMount仅在我第一次呈现主页时调用,当我从其他页面更改路由器时,它无法显示数据,我尝试在componentWillReceiveProps中重新获取主页,它可以工作,但多次获取数据,Constantly当您重新渲染组件时,应再次调用componentDidMount
。谢谢!,使用我发布的代码,componentDidMount和WillMount仅在我第一次呈现主页时调用,当我从其他页面更改路由器时,它无法显示数据,我尝试在componentWillReceiveProps中重新获取主页,它可以工作,但多次获取数据,不断地在重新渲染组件时,应再次调用componentDidMount
。