javascript - 通过 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 的开发者工具并尝试在那里调试,似乎有一个参考错误!但我不明白!怎么可能?
请帮我从不同的角度看。
解决方案
你得到一个有效的 personIndex 了吗?可能你应该写 findIndex(person => person.id === id)
推荐阅读
- firebase - 我如何以列表形式显示来自云 Firestore 的数据并在颤动中传递给另一个文件
- sql - SQL:计算一个城镇和多个其他位置之间的距离
- rsa - 只能在 Windows 10 上的 PuTTYgen 中创建 SSH-1 RSA 密钥对
- java - 为什么我的 TableLayout 不匹配不同类型的 android 屏幕?
- android - 从 Kotlin android 中的 json 字符串中删除换行符 \n
- c# - 如何区分代码中的 2 个或多个输入字段
- javascript - 在 Puppeteer 1.4.0 中单击框架内的元素
- javascript - 如何关闭编译但仍为未编译的“扩展”提供接口 API
- ibm-doors - 如何在 IBM Rational DOORS 中导入电子表格
- visual-studio-code - 如何在 VSCode 中禁用斜体?