我见过两者可以互换使用。
两者的主要用例是什么?有优点/缺点吗?一种更好的做法吗?
这两种方法不可互换。使用 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 */ };
},
});
constructor
和 getInitialState
的区别在于 ES6 和 ES5 本身的区别。
getInitialState
与 React.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.createClass
和 React.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([]);
请注意,初始状态作为参数传递给 useState
; useState([])
阅读有关反应挂钩的更多信息from the official docs
useState
。
super()
以及为什么我们将 props 作为参数传递给它们吗? @sudobangbang
好的,最大的区别是从它们的来源开始,所以 constructor
是 JavaScript 中类的构造函数,另一方面,getInitialState
是 React
的 lifecycle
的一部分。
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
如果您使用 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({
});
这些天我们不必在组件内部调用构造函数 - 我们可以直接调用 state={something:""}
,否则之前我们首先使用 super()
声明构造函数以继承 React.Component
类的所有内容,然后在构造函数内部初始化我们的状态。
如果使用 React.createClass
,则使用 getInitialState
方法定义初始化状态。
最大的区别是从它们的来源开始,因此构造函数是 JavaScript 中类的构造函数,另一方面, getInitialState 是 React 生命周期的一部分。构造函数方法是一种特殊的方法,用于创建和初始化使用类创建的对象。
在构造函数中,我们应该始终初始化状态。
不定期副业成功案例分享
this.state
。请注意,这是唯一允许这样做的地方。您应该在其他任何地方使用this.setState()
。props
作为参数添加到构造函数。同样super()
在这里会很好props
传递给super()
(facebook.github.io/react/docs/…)。但我不知道该建议的原因。没错,实际上不需要将props
传递给super()
,因为this.props
仍然可以在render()
和其他方法中访问。也许建议是为了与潜在的未来功能兼容。this.state
。我建议制作接受(state, props)
并返回新状态的函数,以便您可以在构造函数中执行this.state = myFn(null, props)
或在其他任何地方执行this.setState(myFn)
。