Skip to content

Latest commit

 

History

History
71 lines (59 loc) · 1.49 KB

05.mutating-state.md

File metadata and controls

71 lines (59 loc) · 1.49 KB

不使用setState() 去操作state

导致的问题

  • 在state改变时组件不会重新渲染.
  • 在未来某个时候如果通过setState改变了state, 那么这次未通过setState去改变的state将会同样生效.

坏实践

class SampleComponent extends Component {
  constructor(props) {
    super(props);

    this.state = {
      items: ['foo', 'bar']
    };

    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    // 坏实践: 我们手动更改了state而不是通过setState函数.
    this.state.items.push('lorem');

    this.setState({
      items: this.state.items
    });
  }

  render() {
    return (
      <div>
        {this.state.items.length}
        <button onClick={this.handleClick}>+</button>
      </div>
    )
  }
}

好实践

class SampleComponent extends Component {
  constructor(props) {
    super(props);

    this.state = {
      items: ['foo', 'bar']
    };

    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    // 我们使用了setState()方法来更新state, 组件将会在state更改后被更新.
    this.setState({
      items: this.state.items.concat('lorem')
    });
  }

  render() {
    return (
      <div>
        {this.state.items.length}
        <button onClick={this.handleClick}>+</button>
      </div>
    )
  }
}

参考资料:

React Design Patterns and best practices by Michele Bertoli.