【问题标题】:componentDidUpdate inner working confuses mecomponentDidUpdate 内部工作让我感到困惑
【发布时间】:2016-07-29 07:04:58
【问题描述】:

我的一个 React 组件收到一个 JSON 数组。并且该组件包含一个componentDidUpdate。我知道这个函数在渲染之前运行,我可以看到 nextProps 和 nextState,所以我可以将它们与当前进行比较。但是内部工作让我感到困惑


这是我的程序的步骤:

  1. 父组件将新更新的列表传递给该组件
  2. 这个组件运行componentDidUpdate:

    • 将旧列表与此更新后的新列表进行比较。找到新添加的项,将其推入该组件的状态(数组调用differenceList
  3. 该组件根据differenceList进行渲染


以下是我放置的 console.log。

//我触发更新列表后

  1. 进入 ComponentWillUpdate
  2. 找到唯一项:“1336”,下一行代码将其推入数组
  3. 应该刚刚用self.setState({differenceList: self.state.differenceList.concat(item.id)});将它推入数组中
  4. 到了 ComponentWillUpdate 的末尾,this.state.differenceList is: [] //what??
  5. 进入渲染函数,this.state.differenceList为:[]
  6. 输入 ComponentWillUpdate //为什么又要输入?
  7. ComponentWillUpdate 结束,this.state.differenceList 为:[]
  8. 进入渲染函数,this.state.differenceList为:["1336"]

为什么#4 显示为空??

#6为什么又进入了componentWillUpdate?是因为我更新了 componentWillUpdate 中的状态吗?但是如果是这样为什么#5显示空状态#8现在再次进入渲染函数后,它突然显示更改状态

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    答案是因为setState是异步的。

    1. <Parent/> 尝试渲染 <Child list={[1, 2, 1336]}/>(第 0 批)
      • willUpdate()nextProps = {list: [1, 2, 1336]} 调用
      • self.setState({differenceList: self.state.differenceList.concat(['1336'])}) // This code is asynchronous, creating Batch 1
      • willUpdate() 结束,this.state 还是一样
      • render()
    2. 治疗批次 1(您的 setState() 电话)
      • willUpdate()nextState = { ... differenceList: ['1336'] }
      • this.state 还没更新
      • willUpdate() 结束
      • render() 新状态

    我不确定我是否说得很清楚,我有点累了。
    无论如何,you should not be using this.setState in componentWillUpdate().
    尝试将componentWillReceiveProps() 用于您的目的。

    【讨论】:

    • 我读了几次那个网站,不敢相信我错过了重要的笔记。非常感谢!异步对我有意义,谢谢!
    猜你喜欢
    • 2015-11-12
    • 2010-12-14
    • 1970-01-01
    • 2011-10-13
    • 2020-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多