Reactjs 在React.js中映射时更好的代码实现

Reactjs 在React.js中映射时更好的代码实现,reactjs,react-native,Reactjs,React Native,我是个新手,我想知道是否有更好的方法来编写下面的函数,同时保持相同的功能?非常感谢您的帮助 let temp; temp= this.state.persons.map(person=> { if (person.id == this.person.id) { person.userInput= this.state.userInput; person.secondInput= th

我是个新手,我想知道是否有更好的方法来编写下面的函数,同时保持相同的功能?非常感谢您的帮助

    let temp;
          temp= this.state.persons.map(person=> {
            if (person.id == this.person.id) {
              person.userInput= this.state.userInput;
              person.secondInput= this.state.secondInput;
              return person;
            } else {
              return person;
            }

我认为您的实现本身没有什么不好的地方。无论是否添加/修改
userInput
secondInput
道具,只要返回person就可以节省几行

temp = this.state.persons.map(person => {
  if (person.id == this.person.id) {
    person.userInput = this.state.userInput;
    person.secondInput = this.state.secondInput;
  }
  return person;  
}
  • 与前面提到的Jayce444一样,ReactJs中的状态不能直接修改,这意味着
    person.userInput=this.State.userInput
    不起作用。您应该改用
    this.setState()
  • Array.prototype.findIndex()将返回满足回调函数测试的元素的索引。提及。使用
    findIndex()
    可能比
    map()
    更优雅

希望对您有所帮助。

请注意,这有一个问题,您正在改变状态。在对象数组上映射时,可以访问的循环变量(在本例中为
person
)是对数组中实际对象的引用,而不是它的副本。所以当你做
person.userInput=this.state.userInput您正在直接变异状态中的人。React中的直接状态突变是不可能的(快速的谷歌搜索可以给你一些很好的解释。
const index = this.state.persons.findIndex(person=>person.id===this.person.id)
const tmpPersons = [...this.state.persons]
tmpPersons[index].userInput= this.state.userInput;
tmpPersons[index].secondInput= this.state.secondInput;
this.setState({persons:tmpPersons})