【问题标题】:this.state vs state in Reactthis.state 与 React 中的状态
【发布时间】:2018-12-09 14:45:33
【问题描述】:

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

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

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

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

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

【问题讨论】:

    标签: javascript reactjs state react-props


    【解决方案1】:

    两种方法的最终结果是相同的。这两种方法都只是设置组件的初始state。值得注意的是class properties are a stage 3 proposal,所以并不是所有的开发环境都可以使用。

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

    【讨论】:

      【解决方案2】:

      实际上它们都绑定到this 指针。 classconstructor中的this

      您完全可以通过this.state 访问本地状态,但在第一种样式中,您可以通过superprops 传递给constructor,然后在state 声明中使用它,如下所示:

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

      太棒了,你可以在constructor 中访问props,是不是很漂亮?我绝对将这种风格用于本地状态声明。

      希望这对您有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-28
        • 2023-03-14
        • 2019-09-04
        • 2018-05-01
        • 2019-02-11
        相关资源
        最近更新 更多