无法在反应中读取未定义的属性“someProperty" [英] Cannot read property 'someProperty' of undefined in react
问题描述
我正在开发一个应用程序,在该应用程序中,我使用状态从一个组件向另一个组件传递 Navlink 中的变量值,然后在输入字段中加载这些接收到的值,然后单击该其他组件中的提交按钮以对值执行某些操作.我的值被正确接收并在我提醒他们时正确显示.但是当我点击提交按钮时,它给出了错误,指向构造函数
<块引用>类型错误:无法读取未定义的属性id"
这是我的代码
class Parent extends React.Component{构造函数(道具){超级(道具);this.state={id:2}}使成为(){返回(<导航链接到={{路径名:'/孩子',状态: {id: this.state.id}}}>编辑</NavLink>))}
我在哪里接收值
class Child extends React.Component{构造函数(道具){超级(道具);this.state = {id:this.props.location.state.id}警报(this.props.location.state.id)//工作正常}setId(e){this.setState({id:e.target.value})}addOrEdit(){//报错警报(this.state.id)//做一点事}使成为(){返回(<div><表格><label>Id</label><输入值={this.state.id} onChange={this.setId.bind(this)} type="text"/><br/><input type="submit" onClick={this.addOrEdit.bind(this)} ></input></表单>
)}}
this.state = {id: this.props.location &&this.props.location.state &&this.props.location.state.id}
<小时>
应该解决您的问题,该问题是由于此组件在没有此上下文的情况下调用的次数或此行在 location
设置之前被执行而引起的.(假设您使用 withRouter
来制作位置道具...)
无论如何,并且与您的问题没有直接关系,在构造函数中从 props 为 state 设置初始值是不好的做法,考虑通过生命周期操纵状态,或者不要在此处使用 state 并直接引用 props
I am working on an application where I pass variable values in a Navlink using state from one component to the other and then load those received values in input fields and click on submit button in that other component to do something with values. My values are received correctly and show up correctly when I alert them. But when I click submit button, it gives error,pointing at the constructor
TypeError: Cannot read property 'id' of undefined
Here is my code
class Parent extends React.Component{
constructor(props) {
super(props);
this.state={id:2}
}
render(){
return(
<NavLink
to={{
pathname: '/Child',
state: {
id: this.state.id
}
}}
>
Edit
</NavLink>
)
)
}
Where I receive the values
class Child extends React.Component{
constructor(props) {
super(props);
this.state = {id:this.props.location.state.id}
alert(this.props.location.state.id)//works fine
}
setId(e){
this.setState({id:e.target.value})
}
addOrEdit(){ //gives error
alert(this.state.id)
//do something
}
render(){
return(
<div>
<form>
<label>Id</label>
<input value={this.state.id} onChange={this.setId.bind(this)} type="text"/><br/>
<input type="submit" onClick={this.addOrEdit.bind(this)} ></input>
</form>
</div>
)
}
}
this.state = {id: this.props.location && this.props.location.state && this.props.location.state.id}
Should fix your issue that caused by times that this component called without this context or this line got excuted before location
set.
(assuming you using withRouter
for making location props be exist...)
Anyhow, and not related directly to your issue, it is bad practice to set initial value for state from props at constructor, consider manipulate state through life cycle either don't use state here and refer to props directly
这篇关于无法在反应中读取未定义的属性“someProperty"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!