【问题标题】:Adding to a state array without the resulting array being read only, in React Native?在 React Native 中添加到状态数组而不生成只读数组?
【发布时间】:2022-01-12 01:37:42
【问题描述】:

我正在编写一个组件,我使用存储在 state 中的数组映射到一个组件。

const [animalList, setList] = useState(['cat', 'dog'])
 {  animalList.map((tag) => {
     return (
        <AnimalButton animalz={tag}/>
      )
   })
 }

我想添加到状态数组以强制使应用重新呈现。我尝试使用 .push 函数执行此操作,将增加的数组存储在一个临时变量中,并将该新数组分配给状态,因为 push() 和 unsplice 不返回实际数组。

 onSubmit={(values, actions) => {
                    actions.resetForm();
                   animalList.push(values.pet)
                   let newList = animalList
                    setList(animalList = newList)
                 }}

但是我收到此错误 [TypeError: "animalList" is read-only]?

有没有办法更改添加到animalList,而我的状态中的结果列表不会变为只读?

【问题讨论】:

    标签: arrays reactjs react-native react-hooks


    【解决方案1】:

    是的,您不能将其推入 const。 但是,您可以使用这种方法。

    setList([...animalList,values.pet])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-06
      • 2022-11-22
      • 2022-11-23
      • 2021-05-31
      • 1970-01-01
      • 1970-01-01
      • 2021-02-22
      相关资源
      最近更新 更多