重绘性能问题 - 在哪里实现shouldComponentUpdate?

时间:2016-10-07 01:30:08

标签: javascript reactjs

我无法确定添加shouldComponentUpdate方法的位置。下面的图片应该充分了解我的页面结构:

enter image description here

问题是每当我输入TextField(受控字段)时,状态更新会导致整个RecordManager重新呈现。如果有50多个Record元素,这显然是一个巨大的性能影响。

我通过在RecordManager中添加以下方法暂时解决了这个问题:

  shouldComponentUpdate(nextProps, nextState) {
    return this.state.newRecordName === nextState.newRecordName;
  }

相关的TextField

  <TextField
    style={styles.textField}
    id="newRecordName"
    hintText={newRecordHintText}
    onChange={this.recordNameChange}
    onKeyDown={this.recordNameKeyDown}
  />

我的解决方案看起来有点像黑客。将shouldComponentUpdate置于Record组件中是不是更好?虽然那时我似乎不得不检查一大堆不同的情况,例如:

shouldComponentUpdate(nextProps, nextState) {
  if (this.props.ratings !== nextProps.ratings) return true;
  if (this.props.updatedAt !== nextProps.updatedAt) return true;
  // potentially 3-4 more fields
  return false;
}

这里的理想解决方案是什么?

以下请求,RecordManager中的其他相关代码:

  recordNameChange = ({ target }) => {
    this.setState({ newRecordName: target.value });
  };

  recordNameKeyDown = (event) => {
    const keyCode = keycode(event);

    if (keyCode === 'enter') {
      this.addRecord();
    } else if (keyCode === 'esc') {
      this.cancelAddRecord();
    }
  };

RecordManager州:

this.state = {
  dialogMessage: '',
  newRecordName: '',
  viewMode: localStorage.getItem('userSettingsViewMode') ||
    viewModes.LIST,
};

1 个答案:

答案 0 :(得分:0)

这听起来像是一个完美的案例,可以通过一种叫做“纯粹渲染”的东西来解决:

你可以浅浅地比较道具,看看它们是否已经改变

React提供了一个附加功能来实现这一目标:

https://facebook.github.io/react/docs/shallow-compare.html

<强>更新

React现在提供了一个名为PureComponent的变量,它可以用浅比较逻辑来实现shouldComponentUpdate