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 初始化状态
基础教程推荐
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- 直接将值设置为滑块 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01