因此,我是个新手,我的大部分学习都是通过观看教程来进行的。因此,在这一点上,我偏离了老师的位置,开始以自己的理解来实现它,然后被抛出以下错误



这是代码

render() {

    let person = null;

    if (this.state.showPerson) {
      person= (
        <div>
          {
            this.state.person.map((el, index) => {
              return <Person
              key={el.id}
              click={this.deletePersonHandler.bind(index)}
              name={el.name}
              age={el.age}
              changed={(event) => this.eventSwitchHandler(event, el.id)} />
            })
          }
       </div>
     );
    }
    return (

实现eventSwitchHandler后发生错误,这是我的开关处理程序代码
eventSwitchHandler = (event, id) => {

  const personInput = this.state.person.find(checkID);

  function checkID (passedID) {
     return passedID.id === id
    }
    console.log("newP")
    const newP = {...personInput}
    console.log(newP)
    newP.name = event.target.value
    console.log(personInput)
    this.setState ({person: newP})
  }

[更新]这是状态
state = {
    person: [
    {id: "name1n", name: "Rohit", age: 24},
    {id: "name2l", name: "Hariom", age: 23},
    {id: "name3g", name: "Vaibhav", age: 58}
  ],
  someOtherState: "Untouched state",
  showPerson: false
}

[更新]这是我的讲师代码,他的名字更改处理程序等于我的eventSwitchHandler

javascript -  react :.map不是一个函数-LMLPHP
再次,我的第一个问题是,为什么会发生.map is not a function错误,而在console.logging的过程中,我观察到了一些我很罕见的东西,并附上了屏幕截图(,为什么两个地方的名称看起来都不相同? )

javascript -  react :.map不是一个函数-LMLPHP

最佳答案

您没有在eventSwitchHandler中正确更新状态

eventSwitchHandler = (event, id) => {

  const personInput = this.state.person.find(checkID);

    function checkID (passedID) {
     return passedID.id === id
    }
    console.log("newP")
    const newP = {...personInput}  // newP is an object here
    console.log(newP)
    newP.name = event.target.value
    console.log(personInput)
    this.setState ({person: newP}) // overwriting person array with object
}

您将其更改为
eventSwitchHandler = (event, id) => {
    const personInputIndex = this.state.person.findIndex(checkID);

    function checkID (passedID) {
     return passedID.id === id
    }
    const newName = event.target.value
    this.setState (prevState => ({
            person: [
                ...prevState.person.slice(0, personInputIndex),
                {...prevState.person[personInputIndex], name: newName},
                ...prevState.person.slice(personInputIndex)
            ]
       })
    )
}

要么
eventSwitchHandler = (event, id) => {
    const personInputIndex = this.state.person.findIndex(checkID);

    function checkID (passedID) {
     return passedID.id === id
    }
    const newName = event.target.value
    this.setState (prevState => ({
            person: Object.assign([], prevState.person, {
               [personInputIndex]: {...prevState.person[personInputIndex], newName
            }})
       })
    )
}

09-18 04:56