gpt4 book ai didi

javascript - React.PureComponent 渲染列表组件中的所有项目

转载 作者:行者123 更新时间:2023-12-02 22:28:42 24 4
gpt4 key购买 nike

我们使用 ReactJS 创建了一个可重用的列表组件。然而,由于性能问题,我们决定实现 - shouldComponentUpdate 方法,其条件是我的列表组件何时渲染

public shouldComponentUpdate(nextProps: TreeItemInternalProps, nextState: {}): boolean {
if (this.props.treeObject.selected !== nextProps.treeObject.selected) {
return true;
}
if (this.props.treeObject.expanded !== nextProps.treeObject.expanded) {
return true;
}
return false;
}

意思是,我只想在列表项复选框的值发生变化时渲染我的组件。

假设,由于某种原因,我不能再这样做了。现在,我的替代方案是使用 PureComponent 进行浅层比较。因此,它应该只渲染发生更改的列表项。然而,即使在使用 PureComponent 之后使用,整个组件也会被渲染。

为了正确解释该场景,请参阅以下屏幕截图 -

  1. 不使用 PureComponent/使用 shouldComponentUpdate 中的条件检查

enter image description here

在这里,您可以看到日志“组件已渲染”仅被调用一次,这意味着,仅针对我在 Prop 中所做的更改(这是相同的要求,我想使用 PureComponent 来实现)

<小时/>
  • 使用 PureComponent
  • enter image description here

    在这里,您可以看到日志“组件已渲染”被调用了 3 次,即使我只更改了第一个列表项的 props。这是使用 PureComponent

    最佳答案

    PureComponent 始终为您渲染,因为您的 PropsState 很可能包含在父组件重新渲染期间在父组件中创建的任何对象或数组。

    正如其他人所说,它对重新渲染进行浅层比较(意味着对象引用不会等于新对象引用,即使它们深度相等),因此父组件充当了它的瓶颈PureComponent 子级,因为每次重新渲染都会重新创建一个全新的对象引用

    如果您真的想使用 PureComponent,则必须将组件中的所有其他 props 简化为基元或对象/数组,这样在每次重新渲染父级时都不会获得新的引用

    问题示例:

    class Todo extends PureComponent {
    render() {
    return <div>this.props.foo</div>;
    }
    }

    class MyTodoList extends Component {
    render () {
    const fooBar = {foo: 'bar'}
    return <Todo fooBar={fooBar} />
    }
    }

    修复示例:

    class Todo extends PureComponent {
    render() {
    return <div>this.props.foo</div>;
    }
    }

    class MyTodoList extends Component {
    render () {
    return <Todo fooBar={props.fooBar} />
    }
    }

    您想要做的最好的事情可能是尽可能提高对象创建的程度,使组件不会在此类更改上重新渲染,或者将每个 Prop 简化为非对象。

    关于javascript - React.PureComponent 渲染列表组件中的所有项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58980174/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com