用 shouldComponentUpdate 处理 reactjs 异步回传数据乱序的问题

https://reactjs.org/docs/optimizing-performance.html

class CounterButton extends React.Component {
  constructor(props) {
    super(props);
    this.state = {count: 1};
  }

  shouldComponentUpdate(nextProps, nextState) {
    if (this.props.color !== nextProps.color) {
      return true;
    }
    if (this.state.count !== nextState.count) {
      return true;
    }
    return false;
  }

  render() {
    return (
      <button
        color={this.props.color}
        onClick={() => this.setState(state => ({count: state.count + 1}))}>
        Count: {this.state.count}
      </button>
    );
  }
}

在这段 this.props 有时候仍会造成异步问题,改成 this.state 有时候可以修复:

if (this.props.color !== nextProps.color) {
  return true;
}
if (this.state.count !== nextState.count) {
  return true;
}
return false;

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *