[英]TypeError: Cannot read property 'name' of null
I have a user object where they are able to edit their info (phone number, email, etc) 我有一个用户对象,他们可以在其中编辑信息(电话号码,电子邮件等)
I am unable to access the input's name
inside the setState
callback and keep getting TypeError: Cannot read property 'name' of null
我无法在
setState
回调中访问输入的name
,并不断获取TypeError: Cannot read property 'name' of null
However when I log the event.target.name
it shows to be there. 但是,当我记录
event.target.name
它显示在那里。
When I change a simple state it works: 当我更改一个简单状态时,它会起作用:
Assuming the state value is the same as the target name. 假设状态值与目标名称相同。
this.setState({ [event.target.name]: value });
I am following this post to update the user object. 我正在关注这篇文章以更新用户对象。
Sorry if this is a duplicate, I could not find what I was looking for. 抱歉,如果重复的话,我找不到我想要的东西。
handleUserChange(event) {
console.log(event.target.name);
const value = event.target.value
this.setState(prevState => ({
user: {...prevState.user, [event.target.name]: value }
}))
}
Edit: I am binding it properly in the class constructor like so: 编辑:我将其正确绑定在类构造函数中,如下所示:
contructor(props) {
super(props);
...
this.handleUserChange = this.handleUserChange.bind(this)
}
React is recycling this event. React正在回收此事件。 So the async call to setState wont know the value of event.target.name since the event is already gone.
因此,对setState的异步调用将不知道event.target.name的值,因为该事件已经消失。 You need to make a copy of the value the same as you did with event.target.value .
您需要像使用event.target.value一样复制该值。
handleUserChange(event) {
console.log(event.target.name);
const name = event.target.name;
const value = event.target.value;
this.setState(prevState => ({
user: {...prevState.user, [name]: value }
}))
}
Other solution: 其他解决方案:
handleUserChange(event) {
event.persist();
const value = event.target.value;
this.setState(prevState => ({
user: {...prevState.user, [event.target.name]: value }
}))
}
Persists the values of the event. 保留事件的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.