为什么下面的代码即使状态改变了也不会导致重呈现?
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})
}发布于 2021-06-08 14:36:20
使用以下方法设置状态:
this.setState(previousState => { this.state.counter = previousState.counter + 1 })将直接修改反应状态,这是应该避免的,并可能导致意外的副作用(如组件不重呈现)。
您似乎想要做的事情(根据以前的状态修改状态),应该这样做:
this.setState(previous => ({ counter: previous.counter + 1 }))
// Or
this.setState(previous => { return { counter: previous.counter + 1 } })它返回更改,因此Reacts可以意识到更改并异步处理它,而不是自己在React控件之外修改它。
发布于 2021-06-08 14:36:55
您正在更新直接状态变量。最好从回调返回不可变的状态,如下所示
this.setState(previousState => {
let counter = previousState.counter + 1
return {...previousState,counter}
})https://stackoverflow.com/questions/67889044
复制相似问题