【问题标题】:How to use array state in React function component?如何在 React 函数组件中使用数组状态?
【发布时间】:2020-02-20 23:32:27
【问题描述】:

我正在尝试为 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 专家的帮助。谢谢!

【问题讨论】:

    标签: reactjs react-state react-functional-component


    【解决方案1】:

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

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

    无论如何,它看起来像在效果中调用 setLabelWidth 将 LabelWidth 设置为一个对象,而不是一个数组。

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


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

    但如果你仍然想用钩子来做这件事并避免错误,我建议你这样做


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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-11
      • 2021-07-06
      • 1970-01-01
      • 2019-08-06
      • 1970-01-01
      • 2019-06-27
      • 2020-04-13
      • 2020-10-18
      相关资源
      最近更新 更多