React 组件从 props 初始化状态

新手上路,请多包涵

在 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;

更新:

我将 setState() 更改为 this.state = {} (感谢 joews),但是,我仍然看不出有什么区别。一个比另一个好吗?

原文由 Levy Moreira 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.1k
2 个回答

应该注意的是,复制永远不会改变状态的属性是一种反模式(在这种情况下直接访问 .props )。如果你有一个最终会改变但以 .props 中的值开头的状态变量,你甚至不需要构造函数调用——这些局部变量在调用父构造函数后被初始化:

 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 的非速记版本。

原文由 Zane 发布,翻译遵循 CC BY-SA 4.0 许可协议

您不需要在组件的 constructor --- 中调用 setState - 直接设置 this.state -cff3b 是惯用的

class FirstComponent extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      x: props.initialX
    };
  }
  // ...
}

请参阅 React 文档 - 将本地状态添加到类 中。

您描述的第一种方法没有优势。这将导致在第一次安装组件之前立即进行第二次更新。

原文由 joews 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题