首页 > 解决方案 > React 类组件:为什么它不会导致重新渲染?

问题描述

为什么即使状态改变,下面的代码也不会导致重新渲染?

  constructor(props) {
    super(props);
    this.state = {
      counter: 1
    };
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick() {
    this.setState(previousState => {this.state.counter  = previousState.counter + 1},()=>{
      console.log(this.state.counter)
    });
  }

但这有效......因为我正在改变 this.state.counter??

  constructor(props) {
    super(props);
    this.state = {
      counter: 1
    };
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick() {
    this.setState(previousState => {this.state.counter  = previousState.counter + 1},()=>{
      console.log(this.state.counter)
    });
  }

我知道较短的代码:

handleClick = () =>{
   this.setState({counter : this.state.counter + 1})
}

标签: reactjs

解决方案


使用以下方式设置状态:

this.setState(previousState => { this.state.counter = previousState.counter + 1 })

将直接修改 React 状态,应该避免这种情况并可能导致意外的副作用(如组件未重新渲染)。

您似乎正在尝试做的事情(根据以前的状态修改状态),应该这样做:

this.setState(previous => ({ counter: previous.counter + 1 }))
// Or
this.setState(previous => { return { counter: previous.counter + 1 } })

它返回更改,因此 React 可以感知更改并异步处理它,而不是在 Reacts 控制之外自己修改它。

相关的 React 文档


推荐阅读