[英]Why does it run in multiples of 2 when state changes in function components?
I have some question in react.我有一些问题要回应。 It's not a big problem, but I don't understand.这不是什么大问题,但我不明白。
I make a components where new data is continuously added to data.我制作了一个组件,其中新数据不断添加到数据中。 It makes sense that two console logs appear at first.首先出现两个控制台日志是有道理的。 Because of Mount and Update.因为挂载和更新。 But next cycle, here is my question.Why do 4 console logs appear?但是下一个周期,这是我的问题。为什么会出现4个控制台日志? and then 8.. and then 16.. and then 32.......然后 8.. 然后 16.. 然后 32..
here is the code.这是代码。
import React, { useState } from 'react'
const Ex = () => {
const [state, setstate] = useState({ test: 'data' })
const handleDate = () => {
const { test } = state
const data = 'new data'
setstate({ test: test + data })
console.log(`test: ${test}`);
}
setTimeout(handleDate, 3000);
return (
<div>
<span>Result: {state.test}</span>
</div>
)
}
export default Ex
It would seem that every time state changes, your component is rendered twice, for whatever reason best known to React.似乎每次 state 更改时,您的组件都会呈现两次,无论出于何种原因,React 最了解。 Now each time it renders, it calls setTimeout to trigger a state change in 3 seconds.现在每次渲染时,它都会调用 setTimeout 以在 3 秒内触发 state 更改。 Each of those changes triggers two more renders, which in turn generate two more setTimeouts, each of which will cause the component to render twice again, and so on and so forth.这些更改中的每一个都会触发另外两次渲染,这又会生成另外两个 setTimeout,每个都会导致组件再次渲染两次,依此类推。
Rather than having a setTimeout inside the render, you should use the useEffect hook to achieve the result you want, namely a self-updating component.你应该使用 useEffect 钩子来获得你想要的结果,即一个自我更新的组件,而不是在渲染中设置一个 setTimeout。 See this answer: React hooks - right way to clear timeouts and intervals看到这个答案: 反应钩子 - 清除超时和间隔的正确方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.