【问题标题】:State changed in componentWillReceiveProps is not showing up in the rendercomponentWillReceiveProps 中更改的状态未显示在渲染中
【发布时间】:2026-02-09 19:30:01
【问题描述】:

我在构造函数中定义了一个状态,就像这样

      this.state={
            datainaccordion:'',

        };

现在在我的 componentWillReceiveProps 中,每次我们收到新的 Props 时我都会更改状态,就像这样,

componentWillReceiveProps(nextProps){
        console.log('something',nextProps);
        if (nextProps.data) {
        this.setState({ datainaccordion: nextProps.data });
       }
       console.log('this.state.datainaccordion ',this.state.datainaccordion);
    }

我可以看到控制台,每次有新数据出现时它都可以正常工作,但是当我控制台在渲染中记录相同的状态时,我看不到这个控制台。这可能是什么原因,为什么会发生? 另一件事是我在我的渲染中放了另一个 console.log('rendering') ,即使这也没有出现。 每次获得新数据时如何使其呈现? 我在这里也添加了渲染部分。

render(){
         console.log('rendering');  // this is not being printed  
        console.log('rung',this.state.datainaccordion);
     // some logic to extract an array out of the data in this .state.datainaccordion and we call it arraytoloop



        return (
            <div>
                     <SomeComponentXYz

                       data={arraytoloop}

                       />
              </div>


       );    }

 }

【问题讨论】:

  • 可以为 render() 添加代码吗?
  • 你确定 shouldComponentUpdate 挂钩没有返回 false 吗?
  • 渲染没问题。如上所述,可能错误在 shouldComponentUpdate 中,或者您从 PureComponent 扩展
  • 嘿,我没有在任何地方使用过 ShouldComponentUpadte。
  • @KirillMatrosov 是的,我从 PureComponent 扩展而来。

标签: javascript reactjs


【解决方案1】:

正如@satyajeet jha 所说的

这个组件是从 PureComponent 扩展而来的。 但是 PureComponent 已经实现了 shouldComponentUpdate

React.PureComponent 的 shouldComponentUpdate() 只是浅比较 对象。 ...
仅在您期望拥有时扩展 PureComponent 简单的道具和状态

你的字段 datainaccordion 是我想的对象。所以 PureComponent 中的 shouldComponentUpdate 将返回 false 并停止更新,因为它不检查新旧对象之间的差异

【讨论】:

  • 嘿,kiril,这是否意味着 PureComponent 的 shouldUpdate 返回设置为 false 作为默认值。我读到 shouldUpdate 的默认返回值为 true。
  • @satyajeetjha 没有“默认值”。有函数 checkShouldComponentUpdate(source file to watch) 用作 PureComponent 中的 shouldComponentUpdate
最近更新 更多