[英]Make React hook step into loop
How can I adjust the below code so that after "loop" button is pressed, and then "change data" button is pressed, I can see the loop print changed data - that is, "bar" not "foo"?如何调整下面的代码,以便在按下“循环”按钮,然后按下“更改数据”按钮后,我可以看到循环打印更改的数据 - 即“bar”而不是“foo”?
https://codesandbox.io/s/react-hooks-playground-forked-gn5ywhttps://codesandbox.io/s/react-hooks-playground-forked-gn5yw
const sleep = async(ms: number) => new Promise(r => setTimeout(r, ms))
const Looper = () => {
const [data, setData] = React.useState<string>('foo')
const runOnce = () => {
console.log(data)
}
const loop = async() => {
while (true) {
runOnce()
await sleep(1000)
}
}
return (
<div>
<button onClick={loop}>Loop</button>
<button onClick={runOnce}>Run once</button>
<button onClick={() => setData('bar')}>Change data in state</button>
</div>
)
}
Since the data
change doesn't result in any visual changes in the component, it doesn't need to be state.由于
data
更改不会导致组件发生任何视觉变化,因此不需要是 state。 The runOnce
function containing the data from the old closure is the problem ( data
is declared with const
, after all - it can't change for a given invocation of loop
)包含来自旧闭包的数据的
runOnce
function 是问题所在(毕竟data
是用const
声明的 - 对于给定的loop
调用它不能改变)
Use a ref instead:改用 ref:
const dataRef = useRef('foo');
const runOnce = () => {
console.log(dataRef.current)
}
<button onClick={() => { dataRef.current = 'bar'; }}>Change data in state</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.