首页 > 解决方案 > 动态替换数组中的 JSON 对象

问题描述

我有一个颜色选择器组件,它在选择颜色时将JSON具有该值的对象添加rgba到已经存在arraythis.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,
            },
        }
    );
};

不管这可能工作得多么好,它不是很可重用。例如,如果我想在 中添加第三个objectarray我必须更新该函数以支持另一个index具有该name值的函数。

我一直在寻找一种方法来动态添加,objectsarray在解决方案中出现了不足。

有什么建议么?

我只能访问index可用于查找当前对象的对象,因为它包含有关andthis.state.style.colors的所有必要信息。nameprevState

感谢您的任何帮助或指导

标签: javascriptarraysreactjs

解决方案


你可以使用Array.prototype.splice()

在此示例中,索引 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
    }
  })
}

推荐阅读