首页 文章

React PureComponent中的shouldComponentUpdate实现

提问于
浏览
1

我在我的React应用程序中使用 PureComponent 以获得更好的性能,它有 props 但我不希望它在 props 更改时运行render方法 . 我知道我们不能在 React.PureComponent 中使用 shouldComponentUpdate ,但我的问题是:

有没有办法避免更新 React.PureComponent

我希望这个组件根本不更新/渲染 .

编辑:我在pureComponent中使用 shouldComponentUpdate 时收到此警告:

警告:GameObjectFall有一个名为shouldComponentUpdate()的方法 . 扩展React.PureComponent时不应使用shouldComponentUpdate . 如果使用了shouldComponentUpdate,请扩展React.Component .

3 回答

  • 0

    PureComponent 更改生命周期方法shouldComponentUpdate并添加一些逻辑以自动检查组件是否需要重新渲染 . 这允许PureComponent仅在检测到状态或道具的更改时才调用方法呈现,因此,可以在不必编写额外检查的情况下更改许多组件中的状态 .

    但是,您还可以使用经过验证的方法 shouldComponentUpdate 手动确定重新渲染的必要性 . 它不会覆盖PureComponent逻辑,但会添加您在 shouldComponentUpdate 的自定义实现中添加的任何其他内容

    请参阅说明此内容的片段

    class App extends React.Component {
      state = {
        count1: 0,
        count2: 0,
        count3: 0
      }
      
      increment = (key) => {
         this.setState(prevState => ({[key]: prevState[key] + 1}))
      }
      
      render() {
        console.log('render parent');
        return (
          <div>
             {this.state.count1}
             <Child count={this.state.count1} countNew={this.state.count3}/>
             <button onClick={() => this.increment('count1')}>IncrementOne</button>
             <button onClick={() => this.increment('count2')}>IncrementTwo</button>
          </div>
        )
      }
    }
    
    class Child extends React.Component {
       shouldComponentUpdate(nextProps, nextState) {
          console.log('scu');
          if (nextProps.count !== this.props.count) {
            return false;
          }
       }
       render() {
           console.log('render child');
          return (
            <div>Child: {this.props.count}</div>
          )
       }
    }
    ReactDOM.render(<App/>, document.getElementById('app'));
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
    <div id="app"/>
    
  • 0

    根据PureComponent Documentation,它只在 shouldComponentUpdate() 进行浅层比较 . 因此,如果所有道具都包裹在一个对象中,并且如果改变该对象中的属性,则组件将不会重新渲染,因为浅层比较将始终为true .

    假设为 propContainer = {name: "John", age: "20"}this.props.container = propContainer ,则 propContainer 对象内的变异(更改名称,年龄值)将不会重新呈现该组件 .

  • 3

    当使用 PureComponent 时,方法 shouldComponentUpdate 有一个实现,它只进行浅层比较 . 当你的道具是布尔,字符串或任何其他原始类型时,你应该使用它 .

    您可以将实现实现为 shouldComponentUpdate ,这将覆盖默认的浅层比较 .

    当我说浅层比较时,我的意思是如果你在对象/数组之间进行比较,你会得到错误的比较 . 例如:

    const first = { key: 'value' };
    const second = { key: 'value' };
    if (first === second) {
        // You won't get here
    }
    

相关问题