【问题标题】:Proper way of defining/initializing state in reactjs or react-native在 reactjs 或 react-native 中定义/初始化状态的正确方法
【发布时间】:2019-06-15 12:46:22
【问题描述】:

到目前为止,我了解有两种方法可以在 react 类中定义状态。

第一个使用的人多,如下:

import React, { Component } from "react";
import { View, Text } from "react-native";

export default class Test extends Component {

  constructor (props) {
     super(props)
     this.state = {
       text: 'hello'
     }
  }

  render() {
    return (
      <View>
        <Text>{this.state.text}</Text>
      </View>
    );
  }
}

第二个如下:

import React, { Component } from "react";
import { View, Text } from "react-native";

export default class Test extends Component {

  state = {
     text: "hello"
  }

  render() {
    return (
      <View>
        <Text>{this.state.text}</Text>
      </View>
    );
  }
}

区别在于是否使用构造函数。效果是什么,两者之间有什么区别吗?如果有,我应该使用哪一个?

谢谢!

【问题讨论】:

标签: reactjs react-native


【解决方案1】:

这两种方法都是正确的。确保您在 babelrc 中启用了对类属性的支持。如果您使用的是 CRA,两者都可以。如果你想从 props 中播种初始状态,构造函数 1 会更好看。

【讨论】:

    【解决方案2】:

    这两种方法都很好。第二种是速记法

    【讨论】:

      猜你喜欢
      • 2019-03-12
      • 2018-08-22
      • 2021-07-09
      • 2016-04-04
      • 2016-12-29
      • 2022-06-25
      • 2018-12-31
      • 1970-01-01
      • 2020-10-30
      相关资源
      最近更新 更多