小编典典

在React中this.state与state

reactjs

我正在使用新的代码库。通常,我会在React组件中设置如下状态:

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

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

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

这样做有好处吗?他们似乎只在不需要更改状态时才这样做。我一直认为状态是React处理的东西。这可以做吗?


阅读 279

收藏
2020-07-22

共1个答案

小编典典

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

我个人喜欢使用class字段变体,如果在构造函数中没有做任何其他事情,因为它编写的代码更少,并且您无需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>
  );
}
2020-07-22