在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()更改为这个。state ={}(谢谢joews),然而,我仍然没有看到区别。哪个更好?


当前回答

你可以在需要的时候使用键值重置状态,传递道具给状态,这不是一个好的做法,因为你在一个地方有不受控组件和受控组件。数据应该在一个地方处理 读到这 https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-uncontrolled-component-with-a-key

其他回答

你不需要在组件的构造函数中调用setState——这是习惯用法。国家直接:

class FirstComponent extends React.Component {

  constructor(props) {
    super(props);

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

参见React文档-向类中添加本地状态。

你描述的第一种方法没有任何优势。这将导致在第一次挂载组件之前立即进行第二次更新。

如果你想将所有的道具添加到状态中并保留相同的名称,你可以使用如下所示的简短形式。

constructor(props) {
    super(props);
    this.state = {
       ...props
    }
    //...
}

你可以在需要的时候使用键值重置状态,传递道具给状态,这不是一个好的做法,因为你在一个地方有不受控组件和受控组件。数据应该在一个地方处理 读到这 https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-uncontrolled-component-with-a-key

在构造函数中像这样设置状态数据

constructor(props) {
    super(props);
    this.state = {
      productdatail: this.props.productdetailProps
    };
}

如果你通过props在side componentDidMount()方法中设置,它将不会工作。

如果你直接从props初始化状态,它会在React 16.5中显示警告