javascript - 动态替换数组中的 JSON 对象
问题描述
我有一个颜色选择器组件,它在选择颜色时将JSON
具有该值的对象添加rgba
到已经存在array
的this.state.style.colors
.
这是目前实现的
onColorHandler = (color: any, index: number) => {
let colors;
if (index === 0) {
colors = [
{
name: 'Background',
color: {
rgb: color.rgb,
},
},
this.state.style.colors[1],
this.state.style.colors[2],
];
} else if (index === 1) {
colors = [
this.state.style.colors[0],
{
name: 'Heading',
color: {
rgb: color.rgb,
},
},
this.state.style.colors[2],
];
}
this.setState(
{
style: {
colors,
},
}
);
};
不管这可能工作得多么好,它不是很可重用。例如,如果我想在 中添加第三个object
,array
我必须更新该函数以支持另一个index
具有该name
值的函数。
我一直在寻找一种方法来动态添加,objects
但array
在解决方案中出现了不足。
有什么建议么?
我只能访问index
可用于查找当前对象的对象,因为它包含有关andthis.state.style.colors
的所有必要信息。name
prevState
感谢您的任何帮助或指导
解决方案
在此示例中,索引 2 的蓝色将根据索引变量的值替换为番茄颜色。
const index = 2
const array = ['red', 'green', 'blue', 'orange']
const color = 'tomato'
const output = array.splice(index, 1, color)
console.log(array)
在您的反应 ap 上下文中,您可以通过更改克隆数组并将其新值设置为状态来执行相同操作,就像这样
onColorHandler = (color: any, index: number) => {
const colors = this.state.style.colors.slice() // clone array
colors.splice(index, 1, color) // mutate array
this.setState({
style: {
colors
}
})
}
推荐阅读
- javascript - 在angularjs中循环多个数组,其中包含对象
- clojure - 为什么 Clojure 有 Promise Deliver 功能?
- mongodb - Mongodb 相当于 RIGHT JOIN - 数据可能在集合 A 或 B 中,我应该合并集合还是查找两次?
- erlang - 我可以从远程节点调用 GenServer 客户端函数吗?
- angular - Angular 5无法引导选择指令它不起作用
- tensorflow - 仅具有某些可训练元素或其他自定义方案的张量
- arrays - Excel:如何将多个条件添加到中位数和第一四分位数的数组计算中
- file - How to write date and time to a file name?
- mongodb - MongoDB中唯一的多键哈希索引
- python - 无法安装 requirements.txt