React 组件从 props 初始化状态
2022-08-30 00:30:03
在 React 中,这两种实现之间有什么真正的区别吗?有些朋友告诉我,这就是模式,但我不明白为什么。这似乎更简单,因为渲染只调用一次。FirstComponent
SecondComponent
第一:
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;
更新:我改成了(谢谢joews),但是,我仍然没有看到区别。一个比另一个更好吗?setState()
this.state = {}