【发布时间】: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