如何在ReactJS中动态更新状态值的键?

时间:2019-07-26 10:28:35

标签: reactjs

我的状态值是

this.state = {
    str: {
        key1: "value1",
        key2: "value2",
    }
}

keyvalue是动态设置的。如果我从文本框值更改了动态设置的key,如何在状态下更新key

我的句柄功能是

handleChange(e) {
    const name = "key1a"
    const value = "value1"
    if(this.state.str.hasOwnProperty("key1") {
        /* I want to change the key1 to key1a here! */
    }
}

我所需的状态值应该是

this.state = {
    str: {
        key1a: "value1",
        key2: "value2",
    }
}

3 个答案:

答案 0 :(得分:1)

使用组合键或Object.entires().reduce()查找要更改的键,并为新的状态对象保留其值。

handleChange(e) {
    const { str } = this.state
    const name = "key1a"
    const value = "value1"
    const allPairssWithoutKey1 = null


    if(this.state.str.hasOwnProperty("key1") {
       allPairssWithoutKey1 = Object.entries(str).reduce((acc, [key, value]) => {
           if(key !== "key1"){
              acc[key] = value
           } else {
              acc[name] = value
           }
           return acc
       }, {})
    }

    this.setState({
       str: allPairssWithoutKey1 
    })
}

答案 1 :(得分:0)

这是使用对象分解的更简单方法进行的方式,


    handleChange(e) {
      const name = 'key1a';
      const value = 'value1';
      if (this.state.str.hasOwnProperty("key1")) {
        const { ["key1"]: replaceKey, ...other } = this.state.str;
        this.setState({
          str: {
            ...other,
            [name]: value
          },
        });
      }
    }

答案 2 :(得分:0)

data.table