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 初始化状态
基础教程推荐
- 如何添加到目前为止的天数? 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- Bokeh Div文本对齐 2022-01-01
