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

时间:2019-04-05 01:21:38

标签: 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>
        );

Child组件看起来像这样:

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

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

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

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

1 个答案:

答案 0 :(得分:5)

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

由于您要在每个渲染上创建一个新数组,因此每次Parent渲染都将是一个新数组。

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