不使用setState() 去操作state

导致的问题

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

坏实践

  1. class SampleComponent extends Component {
  2. constructor(props) {
  3. super(props);
  4. this.state = {
  5. items: ['foo', 'bar']
  6. };
  7. this.handleClick = this.handleClick.bind(this);
  8. }
  9. handleClick() {
  10. // 坏实践: 我们手动更改了state而不是通过setState函数.
  11. this.state.items.push('lorem');
  12. this.setState({
  13. items: this.state.items
  14. });
  15. }
  16. render() {
  17. return (
  18. <div>
  19. {this.state.items.length}
  20. <button onClick={this.handleClick}>+</button>
  21. </div>
  22. )
  23. }
  24. }

好实践

  1. class SampleComponent extends Component {
  2. constructor(props) {
  3. super(props);
  4. this.state = {
  5. items: ['foo', 'bar']
  6. };
  7. this.handleClick = this.handleClick.bind(this);
  8. }
  9. handleClick() {
  10. // 我们使用了setState()方法来更新state, 组件将会在state更改后被更新.
  11. this.setState({
  12. items: this.state.items.concat('lorem')
  13. });
  14. }
  15. render() {
  16. return (
  17. <div>
  18. {this.state.items.length}
  19. <button onClick={this.handleClick}>+</button>
  20. </div>
  21. )
  22. }
  23. }

参考资料:

React Design Patterns and best practices by Michele Bertoli.