React中的this.state vs state [英] this.state vs state in React

查看:107
本文介绍了React中的this.state vs state的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm working in a new codebase. Normally, I would set up state like this in a React component:

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'
     }
    ....

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

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. Is this an ok thing to do?

推荐答案

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

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.

示例

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>
  );
}

这篇关于React中的this.state vs state的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆