【问题标题】:Updating state inside nested array when mapping the parent映射父级时更新嵌套数组内的状态
【发布时间】:2020-05-01 12:54:03
【问题描述】:

我正在尝试使用映射函数和扩展运算符更新嵌套数组中的状态,但我不明白如何获取键/值对中的键来选择嵌套对象。有一个箭头在有问题的部分的代码中。

export default class ControlPanel extends Component {
  state = {
    words: 
    [
      { 
        word: "a",
        id: 1,
        column: 1,
        synonymns: {
          all:[],
          selected:[],
          noneFound: false
        }
      }
    ]
  }
}

updateSynonymnState = (wordId, theSynonymns) => {
  const { words } = this.state

  const newWords = words.map(word => {
    if(word.id == wordId){
      return {...word, synonymns.all: theSynonymns} //<--- synonymns.all is throwing an error, but that is the key that i need.
    } else {
      return word
    } 
  })

  this.setState ({words: newWords})
}

我可以从一开始就映射同义词,但是我会丢失我需要选择正确单词的单词的 Id..

我如何在 word.map 函数中设置synonymns.all = theSynonymns,或者在映射父参数时我应该能够以不同的方式设置嵌套的键/值对吗?

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    具有嵌套值的不可变逻辑可能会变得非常棘手。有很多图书馆也关注这一点。例如:Immerimmutability-helperimmutable-js 等等。

    如果您不想使用其他库进行状态转换,那么您必须做更多的工作。您需要将每个状态从主对象分散到您正在修改的部分。

    if (word.id == wordId) {
      return { ...word, synonyms: { ...word.synonyms, all: theSynonymns } }; //<--- synonymns.all is throwing an error, but that is the key that i need.
    } else {
      return word;
    }
    

    【讨论】:

      【解决方案2】:

      您还必须在word 中传播synonymns。这是执行此操作的示例语法:

      const words = [{
        word: "a",
        id: 1,
        column: 1,
        synonymns: {
          all: [],
          selected: [],
          noneFound: false
        }
      }]
      
      const theSynonymns = ['b'];
      
      const newWords = words.map(word => {
        return {
          ...word,
          synonymns: {
          	...word.synonymns,
            all: theSynonymns
          }
        }
      })
      
      
      
      
      console.log(newWords)

      【讨论】:

        猜你喜欢
        • 2018-05-07
        • 1970-01-01
        • 2021-05-27
        • 2019-02-14
        • 2017-04-30
        • 1970-01-01
        • 2021-11-01
        • 1970-01-01
        • 2020-09-25
        相关资源
        最近更新 更多