小编典典

无法读取React中未定义的属性“ someProperty”

reactjs

我正在开发一个应用程序,在该程序中,我使用一个组件中的状态将变量值传递给另一个组件,然后在Navlink中传递变量值,然后将接收到的值加载到输入字段中,然后单击该其他组件中的Submit按钮对值进行处理。我的值被正确接收并在提醒它们时正确显示。但是当我单击提交按钮时,它给出了错误,指向构造函数

TypeError:无法读取未定义的属性“ id”

这是我的代码

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

我在哪里获得价值

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

阅读 438

收藏
2020-07-22

共1个答案

小编典典


 this.state = {id: this.props.location && this.props.location.state && this.props.location.state.id}

应该解决由该组件在没有此上下文的情况下调用该时间或此行在location设置之前被占用的时间所引起的问题。(假设您withRouter用于制作位置道具…)

无论如何,并且与您的问题没有直接关系,不正确的做法是在构造函数中从props设置状态的初始值,考虑通过生命周期操纵状态,或者不在此处使用state并直接引用props

2020-07-22