本文翻译自:What is the difference between using constructor vs getInitialState in React / React Native?

I've seen both used interchangeably. 我看过两者都可以互换使用。

What are the main use cases for both? 两者的主要用例是什么? Are there advantages / disadvantages? 有优点/缺点吗? Is one a better practice? 这是一个更好的做法吗?


#1楼

参考:https://stackoom.com/question/24gEQ/在React-React-Native中使用构造函数与getInitialState有什么区别


#2楼

The two approaches are not interchangeable. 这两种方法不可互换。 You should initialize state in the constructor when using ES6 classes, and define the getInitialState method when using React.createClass . 您应该在使用ES6类时在构造函数中初始化状态,并在使用React.createClass时定义getInitialState方法。

See the official React doc on the subject of ES6 classes . 请参阅有关ES6课程主题的官方React文档 。

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

is equivalent to 相当于

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

#3楼

The difference between constructor and getInitialState is the difference between ES6 and ES5 itself. constructorgetInitialState之间的区别在于ES6和ES5本身之间的区别。
getInitialState is used with React.createClass and getInitialStateReact.createClass和。一起使用
constructor is used with React.Component . constructorReact.Component一起React.Component

Hence the question boils down to advantages/disadvantages of using ES6 or ES5 . 因此,问题归结为使用ES6或ES5的优点/缺点。

Let's look at the difference in code 我们来看看代码的差异

ES5 ES5

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

ES6 ES6

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

There is an interesting reddit thread regarding this. 有一个有趣的reddit线程 。

React community is moving closer to ES6 . React社区正在向ES6靠拢。 Also it is considered as the best practice. 它也被认为是最佳实践。

There are some differences between React.createClass and React.Component . React.createClassReact.Component之间存在一些差异。 For instance, how this is handled in these cases. 例如,如何this是在这些情况下进行处理。 Read more about such differences in this blogpost and facebook's content on autobinding 关于此博客 帖子和facebook的自动绑定内容的差异

constructor can also be used to handle such situations. constructor也可用于处理此类情况。 To bind methods to a component instance, it can be prebinded in the constructor . 要将方法绑定到组件实例,可以在constructor对其进行预绑定。 This is a good material to do such cool stuff. 这是做这么酷的东西的好材料。

Some more good material on best practices 关于最佳实践的一些更好的材料
Best Practices for Component State in React.js React.js中组件状态的最佳实践
Converting React project from ES5 to ES6 将React项目从ES5转换为ES6

Update: April 9 2019 : 更新:2019年4月9日

With the new changes in Javascript class API, you don't need constructor. 随着Javascript类API的新变化,您不需要构造函数。

You could do 你可以做到

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

This will still get transpiled to constructor format, but you won't have to to worry about it. 这仍然会被转换为构造函数格式,但您不必担心它。 you can use this format that is more readable. 你可以使用这种更具可读性的格式。

With React Hooks 使用React Hooks

From React version 16.8, there's a new API Called hooks. 从React版本16.8开始,有一个新的API Called钩子。

Now, you don't even need a class component to have state. 现在,您甚至不需要类组件来拥有状态。 It can even be done in a functional component. 它甚至可以在功能组件中完成。

import React, { useState } from 'react';function TodoApp () {const items = useState([]);

Note that the initial state is passed as an argument to useState ; 请注意,初始状态作为参数传递给useState ; useState([]

Read more about react hooks from the official docs 阅读官方文档中有关反应钩的更多信息


#4楼

If you are writing React-Native class with ES6, following format will be followed. 如果您正在使用ES6编写React-Native类,将遵循以下格式。 It includes life cycle methods of RN for the class making network calls. 它包括用于进行网络呼叫的类的RN的生命周期方法。

import React, {Component} from 'react';
import {AppRegistry, StyleSheet, View, Text, ImageToastAndroid
} 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({});

#5楼

OK, the big difference is start from where they are coming from, so constructor is the constructor of your class in JavaScript, on the other side, getInitialState is part of the lifecycle of React . 好吧,最大的区别是从它们的来源开始,因此constructor是JavaScript中类的构造函数,另一方面, getInitialStateReact lifecycle的一部分。

constructor is where your class get initialised... constructor是您的类初始化的地方...

Constructor 构造函数

The constructor method is a special method for creating and initializing an object created with a class. 构造函数方法是一种用于创建和初始化使用类创建的对象的特殊方法。 There can only be one special method with the name "constructor" in a class. 在类中只能有一个名为“constructor”的特殊方法。 A SyntaxError will be thrown if the class contains more than one occurrence of a constructor method. 如果类包含多个构造函数方法,则将抛出SyntaxError。

A constructor can use the super keyword to call the constructor of a parent class. 构造函数可以使用super关键字来调用父类的构造函数。

In the React v16 document, they didn't mentioned any preference, but you need to getInitialState if you using createReactClass() ... 在React v16文档中,他们没有提到任何首选项,但如果使用createReactClass()则需要getInitialState ...

Setting the Initial State 设置初始状态

In ES6 classes, you can define the initial state by assigning this.state in the constructor: 在ES6类中,您可以通过在构造函数中指定this.state来定义初始状态:

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

With createReactClass(), you have to provide a separate getInitialState method that returns the initial state: 使用createReactClass(),您必须提供一个单独的getInitialState方法,该方法返回初始状态:

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

Visit here for more information. 访问此处获取更多信息。

Also created the image below to show few lifecycles of React Compoenents: 还创建了下面的图像,以显示React Compoenents的几个生命周期:


#6楼

These days we don't have to call the constructor inside the component - we can directly call state={something:""} , otherwise previously first we have do declare constructor with super() to inherit every thing from React.Component class then inside constructor we initialize our state. 这些天我们不必调用组件内的构造函数 - 我们可以直接调用state={something:""} ,否则先前我们已经用super()声明构造函数来继承React.Component类中的所有东西然后在构造函数中我们初始化我们的状态。

If using React.createClass then define initialize state with the getInitialState method. 如果使用React.createClass则使用getInitialState方法定义初始化状态。

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

  1. java 方法 函数 区别_Java中的构造函数和方法之间的区别

    Java方法一种方法用于探索对象的行为. 我们可以在方法的前面加上访问修饰符. 方法必须具有返回类型,例如void,任何原始类型(int,char,float等),任何Object类型(Integer ...

  2. js中构造函数与普通函数的区别

    构造函数不仅只出现在JavaScript中,它同样存在于很多主流的程序语言里,比如c++.Java.PHP等等.与这些主流程序语言一样,构造函数在js中的作业一样,也是用来创建对象时初始化对象,并且总 ...

  3. 了解React Native中的不同JavaScript环境

    by Khoa Pham 通过Khoa Pham 了解React Native中的不同JavaScript环境 (Get to know different JavaScript environmen ...

  4. 如何在React Native中构建项目并管理静态资源

    by Khoa Pham 通过Khoa Pham 如何在React Native中构建项目并管理静态资源 (How to structure your project and manage stati ...

  5. 我在React Native中构建时获得的经验教训

    by Amanda Bullington 通过阿曼达·布林顿(Amanda Bullington) 我在React Native中构建时获得的经验教训 (Lessons I learned while ...

  6. 如何在React Native中写一个自定义模块

    前言 在 React Native 项目中可以看到 node_modules 文件夹,这是存放 node 模块的地方,Node.js 的包管理器 npm 是全球最大的开源库生态系统.提到npm,一般指 ...

  7. 如何在React Native中记录日志?

    本文翻译自:How to do logging in React Native? 如何为Web开发时在React Native中记录变量,例如使用console.log ? #1楼 参考:https: ...

  8. native react ssh_React Native踩坑笔记(持续更新中...)

    最近发现市场上对React Native开发人员的需求挺多的,自己就想学习一下React Native,多一门技术,好将来买个好价位.嘿嘿! 在学习React Native中碰到了不少坑,再次记录下来 ...

  9. react native中一次错误排查 Error:Error: Duplicate resources

    最近一直在使用react native中,遇到了很多的坑,同时也学习到了一些移动端的开发经验. 今天在做一个打包的测试时,遇到了一个问题,打包过程中报错"Error:Error: Dupli ...

最新文章

  1. fisher's exact test
  2. JavaScript碎片—函数闭包(模拟面向对象)
  3. requests(一): 发送一个json格式的post请求
  4. 舞蹈里需要用计算机的地方,【舞蹈教学论文】计算机多媒体技术在舞蹈教学中的应用(共2080字)...
  5. 1.0jpa 2.0_EasyCriteria 2.0 – JPA标准应该很容易
  6. mysql .myi权限_mysql之引擎、Explain、权限详解
  7. Winform 分页用户自定义控件( ML.Pager.WinControl)
  8. 均匀分布 卡方分布_高等数理统计—第一章 统计分布基础
  9. 空号检测(电话号码状态实时分析)freeswitch模块
  10. redhat8.1网卡配置教程
  11. “双态IT”成就业务“互联网+”转型
  12. Oracle+ogg-00664,OGG采用NET8方式读取ASM中日志报OGG-00664(ORA-12162),配置如下:
  13. 《A Survey on Evolutionary Computation for Complex Continuous Optimization》笔记
  14. CAD高版本窗体阵列LISP_CAD高版本窗体阵列LISP_AutoCAD高版本怎么把阵列对话框调出来?...
  15. python 等值线_绘图系列(1):利用matplotlib绘制等值线图
  16. 微信小程序开发-开发入门(一)
  17. 14 款好用的 iOS 开发工具
  18. 惠普光影精灵7Victus 评测
  19. 找不到d3dx9_36.dll解决方法
  20. 任职母校!原科技厅副厅长,履新985院长

热门文章

  1. Unity3D 中 用quaternion 来对一个坐标点进行旋转的初步体会
  2. CSDN Androidclient开展(两):基于如何详细解释Java使用Jsoup爬行动物HTML数据
  3. 一组数字1-n,随机取走3个,求被取走的数【腾讯前端面试题】
  4. 《Windows Mobile平台应用与开发》写作工作顺利进行中
  5. 20181027 考试记录
  6. iphoneX的适配问题
  7. python 发送 smtp
  8. java中excelAPI的简介
  9. 金山逍遥网 sersync 服务器实时镜像同步方案
  10. zabbix监控Linux系统服务