React component initialize state from props(React 组件从 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?
推荐答案
需要注意的是,复制永远不会改变状态的属性是一种反模式(这种情况下直接访问 .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 初始化状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:React 组件从 props 初始化状态


- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- Flexslider 箭头未正确显示 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- 失败的 Canvas 360 jquery 插件 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01