reactjs - React TypeError:无法读取 null 的属性“propName”
问题描述
我有一个休息 api 项目,我想添加 UI 以响应我的项目,但我有一个错误:
TypeError: Cannot read property 'schoolName' of null
我有 2 个实体我的其余 api 项目和 1 个外键。
我的补偿方法:
我的构造函数:
constructor(props) {
super(props);
this.state = {id:'',firstName:'',lastName:'',email:'',school:''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
组件安装:
componentDidMount() {
fetch('http://localhost:8080/student/getStudent/'+this.props.match.params.id)
.then(response=>{
return response.json();
}).then(result=>{
console.log(result);
this.setState({
id:result.id,
firstName:result.firstName,
lastName:result.lastName,
email:result.email,
schoolName:result.school.schoolName
});
});
}
我使用渲染函数的 handleChange 和 handleSubmit 方法:
handleChange(event) {
const state = this.state
state[event.target.name] = event.target.value;
this.setState(state);
}
handleSubmit(event){
event.preventDefault();
fetch('http://localhost:8080/student/updateStudent/'+this.props.match.params.id,{
method:'PUT',
body: JSON.stringify({
id:this.state.id,
firstName: this.state.firstName,
lastName: this.state.lastName,
email:this.state.email,
schoolName:this.state.school.schoolName
}),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
}).then(response=>{
if(response.status===200){
alert("Student update successfully.");
}
});
}
渲染功能的一部分:
<p>
<label>School Name :</label>
<input type="text" className="form-control" name="schoolName" value={this.state.schoolName} onChange={this.handleChange} placeholder="School Name"></input>
</p>
我尝试单击提交按钮并给了我我提到的错误。其实我不知道问题所在。请问你能帮我吗?
解决方案
handleSubmit
你的函数有错误。
改这个就行
JSON.stringify({
id:this.state.id,
firstName: this.state.firstName,
lastName: this.state.lastName,
email:this.state.email,
schoolName:this.state.school.schoolName // error because this.state.school is null and it is wrong also because you have data in this.state.schoolName
})
对此,
JSON.stringify({
id:this.state.id,
firstName: this.state.firstName,
lastName: this.state.lastName,
email:this.state.email,
schoolName:this.state.schoolName
})
注意:还要确保在componentDidMount
,
this.setState({
id:result.id,
firstName:result.firstName,
lastName:result.lastName,
email:result.email,
schoolName:result.school.schoolName // this is not a type, make sure you have schoolName under result.school
});
不要这样设置状态,
handleChange(event) {
const state = this.state
state[event.target.name] = event.target.value;
this.setState(state);
}
你应该做这个,
handleChange(event) {
this.setState({[event.target.name]:event.target.value});
}
推荐阅读
- wordpress - 使用自定义菜单结构协调 Wordpress 导航菜单
- kdb - KDB - 如果不同的 col = 某个值,则将 col 乘以 -1
- python - 从子记录 Odoo V8 更新父级
- php - PHP:使用 lighttpd 获取用户的 IP 地址
- ruby-on-rails - 需要帮助重构以使用 .where 子句 - ruby on rails
- powershell - 我将如何编写一种方法来遍历 bitBucket 中的每个发布分支并将它们分隔在本地驱动器中自己的文件夹中?
- jquery - /?wc-ajax=checkout 504 错误但仍在付款
- laravel - Laravel Sanctum:机器对机器
- flutter - Flutter - 如何使用 ChangeNotifier 正确获取数据
- sql - 选择查询不返回任何记录