gpt4 book ai didi

reactjs - 如何在 React 函数组件中使用数组状态?

转载 作者:行者123 更新时间:2023-12-04 04:23:23 26 4
gpt4 key购买 nike

我正在尝试将数组状态用于 React 功能组件。

这是我尝试过的代码。

  const inputLabel = Array(5).fill(React.useRef(null));
const [labelWidth, setLabelWidth] = React.useState(0);

React.useEffect(() => {
inputLabel.map((label, i) => {
setLabelWidth({...labelWidth, [i]: label.current.offsetWidth});
});
}, []);

这是我尝试过的,但显示错误 React Hook React.useEffect has missing dependencies: 'inputLabel' and 'labelWidth'
寻求 React 专家的帮助。谢谢!

最佳答案

您提到的错误可以通过几种方式修复 - How to fix missing dependency warning when using useEffect React Hook?

但无论如何这不应该破坏你的应用程序,只是为了警告你。

在任何情况下,它看起来像 setLabelWidth 在效果中调用 setLabelWidth 作为一个对象,而不是一个数组。

总而言之,在这种情况下你根本不需要使用钩子(Hook),你可以在 lop 中使用 { .push() } js 数组方法

for(let i = 0; i < InputLabel.length ; i++) {
LabelWidth.push(InputLabel[i])
}

但如果你仍然想用钩子(Hook)来做这件事并避免错误,我建议这样
   const [labelWidth, setLabelWidth] = React.useState([]);

React.useEffect(() => {
if (labelWidth.length === 0) {
const inputLabel = Array(5).fill(React.useRef(null));
inputLabel.map((label) => {
setLabelWidth([ ...labelWidth, label.current.offsetWidth ]);
}
});
}, [labelWidth, setLabelWidth]);

关于reactjs - 如何在 React 函数组件中使用数组状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58544537/

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