【问题标题】:React lifecycle反应生命周期
【发布时间】:2017-10-02 07:49:12
【问题描述】:

我使用这个to方法来处理组件,componentWillMount初始化主页的数据,当路由器更改(类别页面)时使用componentWillReceiveProps,但是当我从类别页面返回主页时,我知道因为componentWillMount只做一次所以我看不到数据。

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),尽管我试图处理一些条件,请帮我解决这个问题,非常感谢。

【问题讨论】:

    标签: reactjs react-lifecycle


    【解决方案1】:

    您必须在 componentWillReceiveProps 上将 nextProps 设置为 this.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;
            } 
    

    【讨论】:

      【解决方案2】:

      永远不要在componentWillMountconstructor 中获取数据。而是在componentDidMount 中进行。

      componentWillMount

      componentWillMount() 在安装发生之前立即调用。它 在 render() 之前调用,因此同步设置状态 此方法不会触发重新渲染。避免引入任何 此方法中的副作用或订阅。

      componentDidMount

      componentDidMount() 在组件被调用后立即调用 安装。需要 DOM 节点的初始化应该放在这里。如果你 需要从远程端点加载数据,这是一个很好的地方 实例化网络请求。在此方法中设置状态将 触发重新渲染。

      如果尚未收到数据,您可以有条件地呈现您的页面。

      render(){
        return(
          <div>
            {
              data.length > 0 ? 
              <List items={data} /> : 
              <div>Loading...</div>
            }
          </div>
        );
      }
      

      【讨论】:

      • 谢谢!,使用我发布的代码,componentDidMount 和 WillMount 仅在我第一次渲染主页时调用,当我从其他页面更改路由器时它无法显示数据,我尝试重新获取主页componentWillReceiveProps,它可以工作,但它会不断地多次获取数据
      • 当您重新渲染组件时,应该再次调用componentDidMount
      猜你喜欢
      • 2019-01-02
      • 2020-07-20
      • 2017-10-17
      • 2021-05-01
      • 2018-10-25
      • 2019-05-14
      • 2021-03-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多