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

IT技术 javascript reactjs react-router
2021-04-26 02:55:09

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

类型错误:无法读取未定义的属性“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>
        )
    }
}
2个回答

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

应该解决由于此组件在没有此上下文的情况下调用的次数或此行在location设置之前被执行而导致的问题(假设您withRouter用于制作位置props存在...)

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

我建议只对 setId 和 addOrEdit 使用箭头函数。

addOrEdit = (e) => {
    // ...
}

只需打电话给他们:

onChange={this.setId}
onClick={this.addOrEdit}

https://medium.com/@machnicki/handle-events-in-react-with-arrow-functions-ede88184bbb

你也是从 prop 派生状态。最好直接使用 prop。

https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html