React prevState和increment对象属性+1不能正常工作



我有一个处于初始状态的对象,当我按下按钮时,我想增加该对象的属性+1。

(这是一个react原生项目(

我的方法:

constructor(props) {
super(props);
this.state = {
myObject: {
incrementCount: 0, // When i press button it should be increment + 1
decrementCount: 0,
}
}
}
...
onPressButton = () => {
this.setState(
prevState => ({
myObject: {
...prevState.myObject,
incrementCount: this.state.myObject.incrementCount + 1,
},
}),
console.log('TOTAL incrementCount: ', this.state.myObject.incrementCount),
);
};

但当我按下按钮时,我会得到以下行为:

console.log prints 0 for first click, 
1 for second click. 

对象更新发生在控制台日志之后。但我在setState回调中使用了它。

请传递一个函数作为回调,而不是控制台日志。从文档中,回调应该是一个函数,但您正在执行console.log(),而不是传递回调。

setState(更新程序[,回调](

onPressButton = () => {
this.setState(
prevState => ({
myObject: {
...prevState.myObject,
incrementCount: prevState.myObject.incrementCount + 1
}
}),
() =>
console.log(
"TOTAL incrementCount: ",
this.state.myObject.incrementCount
)
);
};

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.0/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
<div id="root"></div>
<script type="text/babel">
class App extends React.Component {
constructor() {
super();
this.state = {
name: "React",
myObject: {
incrementCount: 0, // When i press button it should be increment + 1
decrementCount: 0
}
};
}
onPressButton = () => {
this.setState(
prevState => ({
myObject: {
...prevState.myObject,
incrementCount: prevState.myObject.incrementCount + 1
}
}),
() =>
console.log(
"TOTAL incrementCount: ",
this.state.myObject.incrementCount
)
);
};
render() {
return (
<div>
<p>{this.state.myObject.incrementCount}</p>
<button onClick={this.onPressButton}>Increment</button>
</div>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
</script>

最新更新