gpt4 book ai didi

javascript - 在轮询发生之前状态不会更新

转载 作者:行者123 更新时间:2023-12-02 23:09:33 25 4
gpt4 key购买 nike

下面是正在初始化并传递到子组件中的状态:

const [rowCount, setRowCount] = React.useState<number>(1);

<Foo setRowCount={setRowCount} />

富:

const Foo = (props) => {
const { setRowCount } = props;

const count = React.useRef<number>(0);

useEffect(() => {
setRowCount(rowCount.current);
}, [count.current]);

const bars: Bar[] = A.map(( bar ) => bar);

count.current = bar.length;
}

我遇到的问题是,尽管在 count.current = bar 行设置了 rowCount.current,但在重新获取之前,rowCount 不会更新.length

我不确定是否是因为我错误地使用了 useEffect 或者是否存在其他疏忽。如果我可以提供更多详细信息,请告诉我。

最佳答案

UseEffect 在状态更改时运行。您正在使用 useRef 进行 count 。 useRef 用于当您需要变量或 dom 引用但不需要任何重新渲染时。因此,如果您需要任何重新渲染并需要在更改状态后调用 useEffect 。然后使用useState。

const [count, setCount] = React.useState<number>(1);

关于javascript - 在轮询发生之前状态不会更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57435837/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com