如何在reactjs中设置状态特定参数的特定值

问题描述

this.state = {
  array: [1,2,3],objects: [{ id: 1 },{ id: 2 },{ id: 3 }]
}

如何在不使用setStating整个数组/对象的状态下更改对象或数组的特定值?

类似

this.setState({ array[2]: 5 })
this.setState({ object[0].id: 0 })

解决方法

您可以使用辅助函数在索引处设置元素并返回该新更新的数组

const array = [1,2,3]
const object = [{id: 1},{id: 2},{id: 3}]

const setElementAtIndex = (index,value,array) => [
  ...array.slice(0,index),...array.slice(index + 1)
]

console.log(setElementAtIndex(0,99,array))
console.log(setElementAtIndex(1,array))
console.log(setElementAtIndex(2,array))
console.log(setElementAtIndex(0,{ ...object[0],id: 0 },object))

this.setState({ array: setElementAtIndex(2,5,array) })
this.setState({ object: setElementAtIndex(0,object) })
,

我会使用map

const state = {
     array: [1,3],objects: [{id: 1},{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 });

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...