使用钩子在 React 中用新数组更新状态
我在 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
所以,这是一个非常愚蠢的错误。我正在更新功能组件体内的状态。因此,每次状态更新都会导致重新渲染,从而导致另一个状态更新,依此类推。解决方案是根据某些条件/功能/挂钩进行状态更新。就我而言,我将其添加到 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.