代码之家  ›  专栏  ›  技术社区  ›  Pouya Ataei

通过eventhandler更新状态

  •  4
  • Pouya Ataei  · 技术社区  · 6 年前

    下面的代码是一个双向绑定 反应 ,而只有一种类型,文本和输入值同时更新。

    下面是组件循环:

    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>
        )
    }
    

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

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

    但是,这不起作用,当我试着打字的时候,它就冻结了

    我已经检查了chrom的开发工具并尝试在那里进行调试,似乎有一个引用错误!但我不明白!怎么会这样?

    enter image description here

    请帮助我从不同的角度看问题。

    1 回复  |  直到 6 年前
        1
  •  0
  •   Sv3n    6 年前

    你有没有得到一个有效的人格指标?可能您应该编写findindex(person=>person.id==id)

        2
  •  0
  •   喝茶的螃蟹    6 年前

    似乎是指 this.state.person 未更改,组件将不会重新呈现。 在changenamehandler中尝试以下操作:

    // ...ellipsis code ...
    
    this.setState({ person: [...persons] })
    

    在你的州里, person 已声明,但更新 persons 在里面 setState ,那是类型小姐吗?