简体   繁体   English

为什么当 function 组件中的 state 发生变化时,它会以 2 的倍数运行?

[英]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.

相关问题 运行 function 在 state 在 1 秒后更改时生效,如果没有其他更改 - Run function in useeffect when state changes after 1 second if no other changes 仅当某些钩子状态发生变化时才在钩子中运行辅助函数 - Run helper function in a hook only when some hook state changes 当ui-router状态改变时运行javascript函数? - Run javascript function when ui-router state changes? 状态改变时,vuejs更新所有组件 - vuejs update all components when state changes 当不相关的状态更改时,为什么我的redux容器会呈现? - Why does my redux container render when unrelated state changes? 反应状态与道具-为什么状态更改未反映在组件中? - React State vs. Props - Why are state changes not reflected in components? 当反应变量更改值时,为什么此函数不运行? - Why doesn't this function run when the reactive variable changes value? 当找不到元素时,为什么函数会运行? - Why does the function run when there are no elements found? 为什么_.some在没有迭代器函数的情况下运行? - Why does _.some run when there is no iterator function? 当 state 在 mousemove 上发生变化时反应样式组件的低性能 - React styled-components low performance when state changes on mousemove
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM