【发布时间】:2019-07-15 02:59:47
【问题描述】:
我在从异步函数中设置使用“useState”挂钩创建的状态时遇到问题。
我创建了一个代码笔来演示:https://codepen.io/james-ohalloran/pen/ZdNwWQ
const Counter = () => {
const [count, setCount] = useState(0);
const increase = () => {
setTimeout(() => {
setCount(count + 1);
},1000);
}
const decrease = () => {
setTimeout(() => {
setCount(count - 1);
},1000)
};
return (
<div className="wrapper">
<button onClick={decrease}>-</button>
<span className="count">{count}</span>
<button onClick={increase}>+</button>
</div>
);
};
在上面的例子中,如果你点击“增加”,然后点击“减少”..你最终会得到 -1(我希望它是 0)。
如果这是一个 React 类而不是函数组件,我会假设解决方案是在函数上使用 bind(this),但我没想到这是箭头函数的问题。
【问题讨论】:
-
console.log(count) 高于return 语句会得到什么?
-
为什么要使用 setTimeout?
-
我实际上并没有在我的应用程序中使用 setTimout。我正在等待网络请求完成,然后更改错误列表。这只是同一问题的一个更简单的示例