【问题标题】:React Native PureComponent RenderingReact Native PureComponent 渲染
【发布时间】:2017-12-26 04:48:07
【问题描述】:

Don't bind values in functions in render 部分中阅读 When to Use Component or PureComponent 时提到,而不是这样做 <CommentItem likeComment={() => this.likeComment(user.id)} /> 你应该做<CommentItem likeComment={this.likeComment} userID={user.id} /> 然后有:

class CommentItem extends PureComponent {
  ...
  handleLike() {
    this.props.likeComment(this.props.userID)
  }
  ...
}

因为当调用父级的渲染方法时,会创建一个新函数(带有新引用)并传递给likeComment,这将导致所有子级重新渲染,即使数据本身都是相同的.

我对箭头函数的绑定方式有点困惑,想知道下面的示例是否也会导致不良行为

_keyExtractor = (item, index) => String(index);

render() {
    return (
        <FlatList
            ...
            keyExtractor={this._keyExtractor}
            ...>
        </FlatList>
    );
}

由于FlatList 是一个PureComponent(我相信),如果_keyExtractor 的父容器是FlatList,它的定义是否会导致重新渲染?

【问题讨论】:

    标签: javascript reactjs react-native ecmascript-6


    【解决方案1】:

    他在这里引用的reference是对象引用 如你所知{} === {}false

    在 javaScript 中,函数是对象,因此每次调用渲染时,孩子都必须重新渲染,因为您传递了一个新函数。

    (x => x) === (x => x) // false.
    

    您提供的最后一个示例很好,因为该函数将始终保留其引用。

    【讨论】:

      【解决方案2】:

      希望此代码对您有所帮助:

      export default class PureComponent extends Component {
      shouldComponentUpdate(nextProps, nextState) {
          return shallowCompare(this, nextProps, nextState);
        }
      }
      

      你甚至可以返回这个:

      return !isEqual(this.props, nextProps) || !isEqual(this.state, nextState);
      

      注意:

      import {isEqual} from 'lodash';
      import shallowCompare from 'react-addons-shallow-compare';
      

      不要忘记这些导入。

      这个组件将作为一个完美的 PureComponent。

      【讨论】:

        猜你喜欢
        • 2018-12-26
        • 1970-01-01
        • 1970-01-01
        • 2018-04-14
        • 2021-10-31
        • 2019-01-10
        • 2019-10-28
        • 2019-04-06
        • 1970-01-01
        相关资源
        最近更新 更多