小编典典

从组件反应组件初始化状态

reactjs

在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),但是,我仍然看不到区别。一个比另一个好吗?


阅读 250

收藏
2020-07-22

共1个答案

小编典典

应该注意的是,复制永远不会更改为状态的属性是一种反模式(在这种情况下,只需直接访问.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提供的非简写版本。

2020-07-22