【问题标题】:React PureComponent is updating when it shouldn't beReact PureComponent 在不应该更新的时候更新
【发布时间】:2019-04-05 01:21:37
【问题描述】:

我目前在我的应用程序中使用 PureComponent 父组件和子组件。我希望 PureComponent 仅在状态或道具更改时才更新。为了确保这一点,每次调用它的 componentDidUpdate() 方法时,我都有一个子组件记录一些内容。该应用程序如下所示:

class Parent extends React.PureComponent{
    constructor(props){
        super(props);

        this.state = {
            item1: null,
            item2: null,
            list1: [],
            list2: [],
        }

    render(){
        let combinedList= [...this.state.list1, ...this.state.list2];

        return(
            <React.Fragment>
                <Child myList={combinedList} />
                <OtherChild item={this.state.item1} />
            </React.Fragment>
        );

子组件看起来像这样:

class Child extends React.PureComponent{
    constructor(props){
        super(props);
    }

    componentDidUpdate(){
        console.log("Child updated");
    }

    render(){
        return(
            ....
        );
    }

例如,当 Parent 组件中 item2 的状态发生变化时,Child 组件会记录“Child updated”。我有点困惑,因为子组件没有接收 item1 作为道具,并且它的状态没有改变。发生这种情况是因为父组件重新渲染了它的所有子组件吗?或者可能是因为 Child 对其myList 道具所做的浅比较表明它已经改变了?除了编写我自己的 shouldComponentUpdate() 方法之外,如何防止 Child 在每次 Parent 重新渲染时重新渲染?

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    现在,在Parent 组件的render 函数中,您正在使用combinedList 在每次渲染上创建一个新数组。 PureComponent 切换您的shouldComponentUpdate() 方法以进行浅比较以查看它是否应该更新。由于它很浅,它正在比较参考。

    由于您在每次渲染时都创建了一个新数组,因此每次 Parent 渲染时都会创建一个新数组。

    这里的解决方案实际上取决于您对combinedList 的完整用例。直接看这个例子,我建议你在 state 中设置combinedList。另一种选择是将您的子组件道具拆分为list1list2 道具,而不是myList 道具。

    【讨论】:

    • 啊,是的,我猜这就是发生的事情。该死,好的,谢谢!
    猜你喜欢
    • 2021-05-20
    • 2014-07-30
    • 2010-09-22
    • 1970-01-01
    • 2018-12-04
    • 2020-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多