2017-06-12 21 views
0

当我渲染我的页面时,我正在使用componentWillReceiveProps(nextProps)访问道具。在初始加载时,道具会进入页面,但是,如果我点击内部链接,然后再次点击页面,componentWillReceiveProps(nextProps)似乎会被跳过,所以道具不会加载。从我的阅读看来,这似乎是正确的,我只是不知道解决方案是什么。任何帮助?如果页面未刷新,componentWillReceiveProps会跳过加载

componentWillReceiveProps(nextProps) { 
    const profileCandidateCollection = nextProps.profileCandidate; 
    const profileCandidateCollectionId = profileCandidateCollection._id; 
    const summary = profileCandidateCollection && profileCandidateCollection.summary; 
    console.log("summary: ", summary); 

    this.setState({ 
     summary: summary || '', 
     profileCandidateCollectionId: profileCandidateCollectionId || null 
    }); 
    } 

回答

1

componentWillRecieveProps是一个更新的生命周期方法不安装,它不会叫上最初呈现时,将只得到触发时的道具将更新。

当你点击后退按钮组件将与此周期呈现:

constructor -> componentWillMount -> render 
在周期 componentWillRecieve

不会被调用,一旦组件得到呈现任何变化发生在道具值,那么它会得到调用。

作为每DOC

componentWillReceiveProps()一个安装部件 之前被调用接收新道具。如果您需要更新状态以响应prop更改(例如,重置它),您可以比较this.props 和nextProps,并使用this.setState()以 此方法执行状态转换。

使用初始道具值设置初始值内constructor,就像这样:

constructor(props){ 
    super(props); 
    let data = props.profileCandidate; 
    this.state = { 
     summary: data ? data.summary || null, 
     profileCandidateCollectionId: data ? data.id : '' 
    } 
} 
+0

叶,我只是想你的建议。当我把它放在构造函数中时,'data'对象返回空。 – bp123

+0

在构造函数和'componentWillRecieveProps'方法中都使用,'constructor'将在初始渲染时被调用,并且componentWillRecieveProps'将在道具更新时被调用。 –

+0

谢谢,这工作。虽然它看起来不太优雅。这是'最佳实践'吗? – bp123