React- Cannot read property 'setState' of undefined

前端 未结 3 1024
野的像风
野的像风 2021-02-14 08:11

for some reason, I\'m getting the error \" React- Cannot read property \'setState\' of undefined\". So this.state is never getting updated with the values that the user inputs.

3条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-14 09:08

    edit

    If you're going to follow the pattern of binding in the constructor, make sure you use a correct constructor invocation:

    constructor (props) {
        super(props)
    

    Notice props inside the constructor.

    original answer

    Since it appears you're using ES6 component definitions, you should bind to this within the rendered component:

    
    

    You don't need to define this stuff in the constructor:

     //this doesn't work
     //this.onChangeName = this.onChangeName.bind(this);
     //this.onChangePassword = this.onChangePassword.bind(this);
    

    It also appears that maybe you've left out some code in your example, so I'm not sure if you were trying to get rid of the unnecessary parts for the sake of example or what, but make sure your component is properly structured.

提交回复
热议问题