ChatGPT解决这个技术问题 Extra ChatGPT

在 React / React Native 中使用构造函数与 getInitialState 有什么区别?

我见过两者可以互换使用。

两者的主要用例是什么?有优点/缺点吗?一种更好的做法吗?


a
amgaera

这两种方法不可互换。使用 ES6 类时应在构造函数中初始化状态,使用 React.createClass 时应定义 getInitialState 方法。

See the official React doc on the subject of ES6 classes

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { /* initial state */ };
  }
}

相当于

var MyComponent = React.createClass({
  getInitialState() {
    return { /* initial state */ };
  },
});

使用 setState 而不是 this.state = 更好吗?
在构造函数中,您应该始终直接分配给 this.state。请注意,这是唯一允许这样做的地方。您应该在其他任何地方使用 this.setState()
除非您正在使用它,否则您不需要将 props 作为参数添加到构造函数。同样super()在这里会很好
@inostia React 文档建议始终将 props 传递给 super() (facebook.github.io/react/docs/…)。但我不知道该建议的原因。没错,实际上不需要将 props 传递给 super(),因为 this.props 仍然可以在 render() 和其他方法中访问。也许建议是为了与潜在的未来功能兼容。
@TaylorEdmiston 您需要直接修改 this.state。我建议制作接受 (state, props) 并返回新状态的函数,以便您可以在构造函数中执行 this.state = myFn(null, props) 或在其他任何地方执行 this.setState(myFn)
A
Anupama Karunarathna

constructorgetInitialState 的区别在于 ES6ES5 本身的区别。
getInitialStateReact.createClass
{ 1} 与 React.Component 一起使用。

因此问题归结为使用 ES6 或 ES5 的优点/缺点。

我们来看看代码的区别

ES5

var TodoApp = React.createClass({ 
  propTypes: {
    title: PropTypes.string.isRequired
  },
  getInitialState () { 
    return {
      items: []
    }; 
  }
});

ES6

class TodoApp extends React.Component {
  constructor () {
    super()
    this.state = {
      items: []
    }
  }
};

关于这个有一个有趣的reddit thread

React 社区正在向 ES6 靠拢。它也被认为是最佳实践。

React.createClassReact.Component 之间存在一些差异。例如,在这些情况下如何处理 this。详细了解此类差异 in this blogpost 和 Facebook 的content on autobinding

constructor 也可用于处理此类情况。要将方法绑定到组件实例,可以在 constructor 中预先绑定。 This 是做这些很酷的事情的好材料。

更多关于最佳做法的好材料
Best Practices for Component State in React.js
Converting React project from ES5 to ES6

更新:2019 年 4 月 9 日,:

随着 Javascript 类 API 的新变化,您不需要构造函数。

你可以做

class TodoApp extends React.Component {

    this.state = {items: []}
};

这仍然会被转换为构造函数格式,但您不必担心它。您可以使用这种更具可读性的格式。

https://pbs.twimg.com/profile_images/1055697320673595393/5ufJKreq_bigger.jpg

从 React 版本 16.8 开始,有一个称为 hooks 的新 API。

现在,您甚至不需要类组件来拥有状态。它甚至可以在功能组件中完成。

import React, { useState } from 'react';

function TodoApp () {
  const items = useState([]);

请注意,初始状态作为参数传递给 useStateuseState([])

阅读有关反应挂钩的更多信息from the official docs


您正在使用的 ES 版本上的差异根深蒂固
是不是还有第三种构造对象的方法,作为一个功能性的“状态钩子”? reactjs.org/docs/hooks-state.html 我是 react-native 的新手,所以我可能错了。
嗨@djangofan,我想更新这个有一段时间了。谢谢你把我推向那个方向。我添加了带有类字段的新简写,并添加了带有 React 钩子的 useState
你能解释一下什么是 super() 以及为什么我们将 props 作为参数传递给它们吗? @sudobangbang
A
Alireza

好的,最大的区别是从它们的来源开始,所以 constructor 是 JavaScript 中类的构造函数,另一方面,getInitialStateReactlifecycle 的一部分。

constructor 是你的类被初始化的地方......

构造函数构造函数方法是一种特殊的方法,用于创建和初始化使用类创建的对象。一个类中只能有一个名为“constructor”的特殊方法。如果类包含多次出现的构造函数方法,则会抛出 SyntaxError。构造函数可以使用 super 关键字来调用父类的构造函数。

在 React v16 文档中,他们没有提到任何偏好,但如果您使用 createReactClass(),则需要 getInitialState...

设置初始状态 在 ES6 类中,您可以通过在构造函数中分配 this.state 来定义初始状态:

class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = {count: props.initialCount};
  }
  // ...
}

使用 createReactClass(),您必须提供一个单独的 getInitialState 方法来返回初始状态:

var Counter = createReactClass({
  getInitialState: function() {
    return {count: this.props.initialCount};
  },
  // ...
});

访问 here 了解更多信息。

还创建了下图以显示 React 组件的几个生命周期:

https://i.stack.imgur.com/UaFba.png


我建议将 componentWillReceiveProps 添加到图表中,因为 OP 是关于组件中的状态。
你能解释一下什么是 super() 以及为什么我们将 props 作为参数传递给它们吗? @Alireza
D
David Schumann

如果您使用 ES6 编写 React-Native 类,将遵循以下格式。它包括用于进行网络调用的类的 RN 生命周期方法。

import React, {Component} from 'react';
import {
     AppRegistry, StyleSheet, View, Text, Image
     ToastAndroid
} from 'react-native';
import * as Progress from 'react-native-progress';

export default class RNClass extends Component{
     constructor(props){
          super(props);

          this.state= {
               uri: this.props.uri,
               loading:false
          }
     }

     renderLoadingView(){
          return(
               <View style={{justifyContent:'center',alignItems:'center',flex:1}}>
                    <Progress.Circle size={30} indeterminate={true} />
                    <Text>
                        Loading Data...
                    </Text>
               </View>
          );
     }

     renderLoadedView(){
          return(
               <View>

               </View>
          );
     }

     fetchData(){
          fetch(this.state.uri)
               .then((response) => response.json())
               .then((result)=>{

               })
               .done();

               this.setState({
                         loading:true
               });
               this.renderLoadedView();
     }

     componentDidMount(){
          this.fetchData();
     }

     render(){
          if(!this.state.loading){
               return(
                    this.renderLoadingView()
               );
          }

          else{

               return(
                    this.renderLoadedView()
               );
          }
     }
}

var style = StyleSheet.create({

});

t
ttulka

这些天我们不必在组件内部调用构造函数 - 我们可以直接调用 state={something:""},否则之前我们首先使用 super() 声明构造函数以继承 React.Component 类的所有内容,然后在构造函数内部初始化我们的状态。

如果使用 React.createClass,则使用 getInitialState 方法定义初始化状态。


A
Apurva Aggarwal

最大的区别是从它们的来源开始,因此构造函数是 JavaScript 中类的构造函数,另一方面, getInitialState 是 React 生命周期的一部分。构造函数方法是一种特殊的方法,用于创建和初始化使用类创建的对象。


V
Vishnu Teja

在构造函数中,我们应该始终初始化状态。


正如目前所写的那样,您的答案尚不清楚。请edit添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。您可以找到有关如何写出好答案的更多信息in the help center