this.state vs state in React

让人想犯罪 __ 提交于 2019-12-03 07:04:18

The end result of both approaches is the same. Both approaches are just setting the initial state of the component. It's worth noting that class properties are a stage 3 proposal, so all development environments may not be able to use them.

I personally like to use the class field variant if nothing else is done in the constructor, as it is less code to write, and you have no super call to worry about.

Example

class Component1 extends React.Component {
  state = { value: this.props.initialValue };

  render() {
    return <div> {this.state.value} </div>
  }
}

class Component2 extends React.Component {
  constructor(props) {
    super(props);
    this.state = { value: props.initialValue };
  }

  render() {
    return <div> {this.state.value} </div>
  }
}

function App() {
  return (
    <div>
      <Component1 initialValue={1} />
      <Component2 initialValue={2} />
    </div>
  );
}

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!