this.state vs state in React

后端 未结 2 1974

I\'m working in a new codebase. Normally, I would set up state like this in a React component:

class App extends React.Component {
    constructor() {
        s         


        
2条回答
  •  Happy的楠姐
    2021-02-05 13:05

    Actually both of them bind to this pointer. the this that made in constructor of class.

    Totally you can access to local state by this.state but in first style you can pass props to constructor by super and then use it in state declaration, just like below:

    class App extends React.Component {
        constructor(props) {
            super(props);
            this.state={
                foo: 'bar',
                jaz: props.someParentState,
            }
         }
    ....
    

    Awesome, you can access to props in constructor, isn't pretty? I definitely use this style for local state declaration.

    Hope this helps you.

提交回复
热议问题