【问题标题】:How can I update a value of an element of an array without changing the position in React native using useState?如何在不使用 useState 更改 React Native 中的位置的情况下更新数组元素的值?
【发布时间】:2021-03-31 06:30:57
【问题描述】:

如何在不修改其位置的情况下使用useState 更改数组的特定值。例如:如果我不使用useState,我可以像这样修改数组:checkBox[2] = true。我试过setCheckBox[2](true),但它确实有效。

谁能帮我解决这个问题。

const [checkBox, setCheckBox] = useState(
   [true, false, false, false, false, false, false, false]
);

如何在不更改位置的情况下将此数组的索引 2 中的值更改为 true?

【问题讨论】:

    标签: arrays react-native use-state


    【解决方案1】:

    我认为你可以简单地做

      const myFunction = () => {
        let arrayCopy = [...checkBox]   // or Array.from() in order to avoid reference
        arrayCopy[2] = true
        setCheckBox(arrayCopy)
      }
    

    这样你跳过循环......

    【讨论】:

      【解决方案2】:

      setCheckBox[2](true) - 这不起作用,因为setCheckBox 是一个函数,而不是数组或对象字面量。 setCheckBox[2] 只是在这里使用的语法错误。

      您需要避免直接改变数组。这样做不会触发组件的重新渲染。

      要正确更新状态,在您的情况下,您可以使用.map() 方法来转换checkBox 数组的值。 .map() 方法将返回一个包含转换后的值的新数组。

      // if index is equal to two, return true, otherwise return the value as it is
      const updatedArr = checkBox.map((val, idx) => idx === 2 ? true : val);
      
      // pass the new array to state updater function
      setCheckbBox(updatedArr);
      

      【讨论】:

        猜你喜欢
        • 2021-12-14
        • 1970-01-01
        • 1970-01-01
        • 2020-09-13
        • 2019-08-13
        • 2016-11-03
        • 2011-05-05
        • 2021-11-15
        相关资源
        最近更新 更多