使用钩子在 React 中用新数组更新状态

发布于 2025-01-19 03:52:15 字数 242 浏览 3 评论 0原文

我在 React 功能组件中有一个像这样的数组状态 -

const [columns, setColumns] = React.useState<[]>([])

我希望在某个时候更新整个数组(而不是更新推送/删除某些元素的某些特定元素)。我可以简单地执行 setColumns(newArray) 吗?这样做后,我的 React 组件由于某种原因进入无限循环。请帮忙。

I have a state of array in a React functional component like this -

const [columns, setColumns] = React.useState<[]>([])

I wish to update the entire array at some time (instead of updating some particular element of pushing/deleting some element). Can I simply do setColumns(newArray) ? Upon doing so, my React component is going into an infinite loop for some reason. Pls help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

怂人 2025-01-26 03:52:15

所以,这是一个非常愚蠢的错误。我正在更新功能组件体内的状态。因此,每次状态更新都会导致重新渲染,从而导致另一个状态更新,依此类推。解决方案是根据某些条件/功能/挂钩进行状态更新。就我而言,我将其添加到 useEffect 挂钩中,该挂钩仅在其依赖项之一发生更改时才执行。

So, it was a very silly bug. I was updating the state inside the body of the functional component. As a result, each state update led to a re-render which led to another state update and so on. Solution was to have the state update based on some condition/function/hook. In my case, I added it inside the useEffect hook which executes only when one of it's dependencies changes.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文