[英]How to setState a specific value of a particular parameter in reactjs
this.state = {
array: [1, 2, 3],
objects: [{ id: 1 }, { id: 2 }, { id: 3 }]
}
如何在不設置整個數組/對象的情況下更改 state 中 object 或數組的特定值?
就像是
this.setState({ array[2]: 5 })
this.setState({ object[0].id: 0 })
您可以使用幫助器 function 在索引處設置元素並返回新更新的數組
const array = [1, 2, 3] const object = [{id: 1}, {id: 2}, {id: 3}] const setElementAtIndex = (index, value, array) => [...array.slice(0, index), value, ...array.slice(index + 1) ] console.log(setElementAtIndex(0, 99, array)) console.log(setElementAtIndex(1, 99, array)) console.log(setElementAtIndex(2, 99, array)) console.log(setElementAtIndex(0, {...object[0], id: 0 }, object))
this.setState({ array: setElementAtIndex(2, 5, array) })
this.setState({ object: setElementAtIndex(0, { ...object[0], id: 0 }, object) })
我會使用map
。
const state = { array: [1,2,3], objects: [{id: 1}, {id: 2}, {id: 3}] } const newArray = state.array.map((v, i) => i === 2? 5: v); const newObjects = state.objects.map((v, i) => i === 0? {...v, id: 0}: v); console.log(newArray); console.log(newObjects); // this.setState({...this.state, array: newArray }); // this.setState({...this.state, objects: newObjects });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.