Uncaught TypeError: Cannot read property 'state or props' of undefined

前端 未结 2 1419
[愿得一人]
[愿得一人] 2020-11-22 04:29

So I started converting my application from ES2015 to ES6 which uses React.

I have a parent class and a child class like so,

export default class Par         


        
2条回答
  •  醉酒成梦
    2020-11-22 04:52

    I agree with all different solutions given by @Shubham Kathri except direct binding in render.

    You are not recommended to bind your functions directly in render. You are recommended to bind it in constructor always because if you do binding directly in render then whenever your component renders Webpack will create a new function/object in bundled file thus the Webpack bundle file size grows. For many reasons your component re-renders eg: doing setState but if you place it in constructor it gets called called only once.

    The below implementation is not recommended

    
    

    Do it in constructor always and use the ref wherever required

    constructor(props){
      super(props);
      this.login = this.login.bind(this);
      this.setCodeChange = this.setCodeChange.bind(this);
    }
    
    
    

    If you are using ES6 then manual binding is not required but if you want you can. You can use arrow functions if you want to stay away with scope related issues and manual function/object bindings.

    Sorry if there are any typos I am answering in my mobile

提交回复
热议问题