简体   繁体   English

如何在 React function 组件中使用数组 state?

[英]How to use array state in React function component?

I am trying to use an array state for a React functional component.我正在尝试将数组 state 用于 React 功能组件。

This is the code I tried.这是我尝试过的代码。

  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});
    });
  }, []);

This is what I tried, but showing an error of React Hook React.useEffect has missing dependencies: 'inputLabel' and 'labelWidth'这是我尝试过的,但显示React Hook React.useEffect has missing dependencies: 'inputLabel' and 'labelWidth'

Looking for React experts' help.寻求 React 专家的帮助。 Thanks!谢谢!

the error you mentioned can be fixed in a few ways - How to fix missing dependency warning when using useEffect React Hook?您提到的错误可以通过几种方式修复 - How to fix missing dependency warning when using useEffect React Hook?

but anyhow this isn't supposed to break your app, just to warn you.但无论如何这不应该破坏你的应用程序,只是为了警告你。

in any case, it looks like setLabelWidth called in the effect set LabelWidth as an object, not an array.无论如何,它看起来像在效果集 LabelWidth 中调用的 setLabelWidth 作为 object,而不是数组。

to sum up, you don't have to use hooks at all in this case, you can just use {.push() } js array method in a lop总而言之,在这种情况下你根本不需要使用钩子,你可以在 lop 中使用 {.push() } js 数组方法


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

but if you still wanna do this with hooks and avoid errors I suggest something like that但如果你仍然想用钩子来做这件事并避免错误,我建议这样


   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]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM