React中的this.state vs state

J S*_*olt 9 javascript state reactjs react-props

我正在开发一个新的代码库.通常,我会在React组件中设置这样的状态:

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

在这个新的代码库中,我看到了很多这样的:

class App extends React.Component {
    state={
        foo: 'bar'
     }
    ....
Run Code Online (Sandbox Code Playgroud)

这样做是否有优势?他们似乎只在国家不需要改变时才这样做.我一直认为状态是React处理的东西.这是一件好事吗?

Tho*_*lle 8

两种方法的最终结果是相同的.这两种方法都只是设置state组件的初始值.值得注意的是,类属性是第3阶段提案,因此所有开发环境都可能无法使用它们.

我个人喜欢使用类字段变量,如果在构造函数中没有其他任何操作,因为它编写的代码较少,而且您无需super担心.

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>
  );
}
Run Code Online (Sandbox Code Playgroud)


Ame*_*icA 6

实际上它们都绑定到this指针。的this是,在做 constructor class

完全你可以访问本地状态 bythis.state但在第一种样式中你可以传递props constructor bysuper然后在state声明中使用它,如下所示:

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

太棒了,你可以访问propsin constructor ,是不是很漂亮?我绝对使用这种风格进行本地状态声明。

希望这对你有帮助。