简体   繁体   English

React中的this.state vs state

[英]this.state vs state in React

I'm working in a new codebase. 我正在开发一个新的代码库。 Normally, I would set up state like this in a React component: 通常,我会在React组件中设置这样的状态:

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

In this new codebase, I'm seeing a lot of this: 在这个新的代码库中,我看到了很多这样的:

class App extends React.Component {
    state={
        foo: 'bar'
     }
    ....

Is there an advantage to doing it this way? 这样做是否有优势? They seem to only do it when state doesn't need to be altered. 他们似乎只在国家不需要改变时才这样做。 I always thought of state as being something React handled. 我一直认为状态是React处理的东西。 Is this an ok thing to do? 这是一件好事吗?

The end result of both approaches is the same. 两种方法的最终结果是相同的。 Both approaches are just setting the initial state of the component. 这两种方法都只是设置组件的初始state It's worth noting that class properties are a stage 3 proposal , so all development environments may not be able to use them. 值得注意的是, 类属性是第3阶段提案 ,因此所有开发环境都可能无法使用它们。

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. 我个人喜欢使用类字段变量,如果在构造函数中没有其他任何操作,因为它编写的代码较少,并且您没有super调用需要担心。

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. 实际上它们都绑定到this指针。 the this that made in constructor of class . this是在class constructorconstructor的。

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: 完全可以通过this.state访问本地状态,但是在第一种风格中你可以通过superprops传递给constructor ,然后在state声明中使用它,如下所示:

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? 太棒了,你可以在constructor访问props ,是不是很漂亮? I definitely use this style for local state declaration. 我绝对将这种风格用于当地的州宣言。

Hope this helps you. 希望这对你有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM