gpt4 book ai didi

javascript - React中setState增量和每次增量1有什么区别

转载 作者:行者123 更新时间:2023-11-28 17:16:04 26 4
gpt4 key购买 nike

class App extends React.Component {
constructor(props) {
super(props);
this.state = {
num: 1
}
}
componentDidMount() {
this.setState({
num: this.state.num+1
});
this.setState({
num: this.state.num+1
});
}
render() {
return (
<div>
{ this.state.num }
</div>

)
}
}

在componentDidMount中调用两次setState使用+1更新num,但最终num为2

class App extends React.Component {
constructor(props) {
super(props);
this.state = {
num: 1
}
}
componentDidMount() {
this.setState({
num: ++this.state.num
});
this.setState({
num: ++this.state.num
});
}
render() {
return (
<div>
{ this.state.num }
</div>

)
}
}

setState使用自增的方式更新num,但最终num为3。

这两种方法有什么区别?以及如何理解setState如何更新状态?

谢谢

最佳答案

setState是异步的,返回后this.state还没有改变:

this.setState({
num: this.state.num+1 // this.state.num is 1, so the value here is 2
});
this.setState({
num: this.state.num+1 // this.state.num is still 1, so the value is still 2
});

所以这与

相同
this.setState({
num: 2
});
this.setState({
num: 2
});

但是,在第二个示例中,您正在改变 this.state.num 所以

this.setState({
num: ++this.state.num // this.state.num is 2 after increment
});
this.setState({
num: ++this.state.num // this.state.num is 3 after incrementing again
});

这实际上与

相同
this.setState({
num: 2
});
this.setState({
num: 3
});

一般来说,调用 setState 并根据 this.state 计算新值并不是一个好主意。如果您想根据 state 中的当前值更改状态,请不要访问 this.state!相反,请回调 setState:

setState(state => ({ num: state.num + 1 })

考虑 ReactJS docs 中的这个示例:

For example, if you attempt to increment an item quantity more than once in the same cycle, that will result in the equivalent of:

Object.assign(
previousState,
{quantity: state.quantity + 1},
{quantity: state.quantity + 1},
...
)

Subsequent calls will override values from previous calls in the same cycle, so the quantity will only be incremented once. If the next state depends on the current state, we recommend using the updater function form, instead:

this.setState((state) => {
return {quantity: state.quantity + 1};
});

关于javascript - React中setState增量和每次增量1有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53484077/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com