首页 > 解决方案 > 通过 eventHandler 更新状态

问题描述

下面的一段代码是ReactJS中的双向绑定,其中一种类型是文本和输入值同时更新。

这是组件循环:

if (this.state.personState){

  persons = (

    <div> 

      {this.state.person.map( (person, index) =>{
          return 
             <Person 
                click = {()=>this.deletePerson(index)}
                name = {person.name} 
                age = {person.age} 
                key = {person.id} 
                changed = { (event)=>this.changeNameHandler(event, person.id)} >
             </Person>
      })}

    </div>

)

处理事件的函数

changeNameHandler = (event, id) => {

   const personIndex = this.state.person.findIndex(person => person === id)

   // making a copy and not manipulating the original reference
   const personcpy = { ...this.state.person[personIndex] }

   // assign the value of the event target
   personcpy.name = event.target.value;

   // making a copy of the state to update the dom
   const persons = [...this.state.person]

   // updating...
   persons[personIndex] = personcpy

   // state update
   this.setState({ persons : persons })

}

Javascript 对象本身

state = {
  person : [
    {id:'12121', name:"Jimmy", age:12},
    {id:'121s', name:"Jack", age:15},
    {id:'23232a', name:"pouya", age:27}
  ]
} 

组件代码

const Person = (props) => {
    return (
        <div className="Person" >
        <p  onClick={props.click}>I'm {props.name} and I'm {props.age} years old</p>
        <input  onChange={props.changed} value={props.name} />
        <h1 >{props.name}</h1>
        </div>
    )
}

我知道findIndex()返回数组中满足给定测试的第一个元素的索引。

我正在测试更改事件的索引是否与对象索引相同!

但是,这不起作用,当我尝试键入它时,它会冻结

我检查了 Chrom 的开发者工具并尝试在那里调试,似乎有一个参考错误!但我不明白!怎么可能?

在此处输入图像描述

请帮我从不同的角度看。

标签: javascriptreactjsecmascript-6

解决方案


你得到一个有效的 personIndex 了吗?可能你应该写 findIndex(person => person.id === id)


推荐阅读