React组件从props初始化状态 [英] React component initialize state from props
问题描述
在React中,这两种实现之间是否存在真正的差异?
有些朋友告诉我,FirstComponent是模式,但我不明白为什么。 SecondComponent似乎更简单,因为渲染只被调用一次。
In React, are there any real differences between these two implementations? Some friends tell me that the FirstComponent is the pattern, but I don't see why. The SecondComponent seems simpler because the render is called only once.
第一:
import React, { PropTypes } from 'react'
class FirstComponent extends React.Component {
state = {
description: ''
}
componentDidMount() {
const { description} = this.props;
this.setState({ description });
}
render () {
const {state: { description }} = this;
return (
<input type="text" value={description} />
);
}
}
export default FirstComponent;
第二名:
import React, { PropTypes } from 'react'
class SecondComponent extends React.Component {
state = {
description: ''
}
constructor (props) => {
const { description } = props;
this.state = {description};
}
render () {
const {state: { description }} = this;
return (
<input type="text" value={description} />
);
}
}
export default SecondComponent;
更新:
我将setState()更改为this.state = {}(感谢joews ),但是,我仍然没有看到差异。一个比其他更好吗?
Update: I changed setState() to this.state = {} (thanks joews), However, I still don't see the difference. Is one better than other?
推荐答案
应该注意的是,复制属性的反模式永远不会改变为state(在这种情况下直接访问.props)。如果你有一个最终会改变的状态变量但是从.props的值开始,你甚至不需要构造函数调用 - 这些局部变量在调用父代的构造函数后被初始化:
It should be noted that it is an anti-pattern to copy properties that never change to the state (just access .props directly in that case). If you have a state variable that will change eventually but starts with a value from .props, you don't even need a constructor call - these local variables are initialized after a call to the parent's constructor:
class FirstComponent extends React.Component {
state = {
x: this.props.initialX,
// You can even call functions and class methods:
y: this.someMethod(this.props.initialY),
};
}
这是一个等同于下面@joews答案的简写。它似乎只适用于更新版本的es6转换器,我在一些webpack设置上遇到了问题。如果这对您不起作用,您可以尝试添加babel插件 babel-plugin-transform-class-properties
,或者您可以使用@的非简写版本以下是joews。
This is a shorthand equivalent to the answer from @joews below. It seems to only work on more recent versions of es6 transpilers, I have had issues with it on some webpack setups. If this doesn't work for you, you can try adding the babel plugin babel-plugin-transform-class-properties
, or you can use the non-shorthand version by @joews below.
这篇关于React组件从props初始化状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!