React 类组件:为什么它不会导致重新渲染?

时间:2021-06-08 14:28:12

标签: reactjs

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

  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})
}

2 个答案:

答案 0 :(得分:1)

使用以下方法设置状态:

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 控制之外自己修改它。

Relevant React documentation

答案 1 :(得分:0)

您正在更新直接状态变量。更好地从 setState 回调以不可变方式返回更新状态,如下所示

this.setState(previousState => {
      let counter  = previousState.counter + 1
      return {...previousState,counter}
    })