React PureComponent在不应该更新的时候进行更新

alb*_*ert 2 javascript reactjs

我当前在我的应用程序中使用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>
        );
Run Code Online (Sandbox Code Playgroud)

子组件看起来像这样:

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

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

    render(){
        return(
            ....
        );
    }
Run Code Online (Sandbox Code Playgroud)

例如,当父组件中item2的状态发生变化时,子组件将记录“已更新子组件”。我有点困惑,因为子组件没有收到item1作为道具,并且它的状态没有改变。这是因为“父级”组件放弃了所有子级吗?还是因为Child对它的myList道具所做的浅表比较表明它已经改变了?除了编写自己的shouldComponentUpdate()方法之外,如何防止孩子每次父母重新提交时都重新提交?

LMu*_*vey 5

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

由于您要在每个渲染上创建一个新数组,因此每次渲染时它都会是新的Parent

这里的解决方案实际上取决于您拥有的完整用例combinedList。直接看这个例子,我建议您combinedList进入状态。另一个选择是将您的子组件prop 拆分为a list1list2prop而不是myListprop。