如何在react.js ES6中使用props设置状态

Jos*_*ers 4 ecmascript-6 reactjs webpack

我想知道,如何使用ES6使用props参数设置状态

之前:

const MyComponent = React.createClass({
  getInitialState: function() {
    return {
      name: this.props.name || 'Initial data...'
    };
  }
});
Run Code Online (Sandbox Code Playgroud)

而现在我正在尝试这样做并且this.props不存在:

class MyComponent extends React.Component {
  constructor() {
    super()
      this.state = { name: this.props.name || 'Joseph Flowers' };
  }
}
Run Code Online (Sandbox Code Playgroud)

gsa*_*edo 6

你只需要在构造函数方法中传递props参数:

import React from 'react';

class MyComponent extends React.Component {
    constructor(props) { // <-- this parameter
        super(props)
        this.state = {
            name: props.name || 'Joseph Flowers' // <-- then used like this
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,在某些情况下,它不是反模式:

(对于更复杂的逻辑,只需在方法中隔离计算.)

但是,如果您明确说明prop只是组件内部控制状态的种子数据,那么它不是反模式:来源:https://facebook.github.io/react/tips/props-in-getInitialState-作为抗pattern.html

BTW for ES6如果要设置默认属性,则必须在类声明的下一步声明:

import React from 'react';
import ReactDOM from 'react-dom';

class MyComponent extends React.Component {

    /**
    This is the ES7 way to use
    static propTypes = {            
        name: React.PropTypes.string,
    }

    static defaultProps = {         
        name: 'My default value using ES7'
    }
    */

    constructor(props) {
        super(props)
        // this still could be the best solutions in cases
        // of the unexpected values in the props sent 
        // for the out side component
        this.state = {
            name: props.name && props.name !== '' ? props.name :'Joseph Flowers';
        };
    }
}

// This is the ES6 way to use
MyComponent.propTypes = {
    name: React.PropTypes.string
}

MyComponent.defaultProps = {
    name: 'My default value'
}

ReactDOM.render(<MyComponent name="" />, document.getElementById('my-container-id'));
Run Code Online (Sandbox Code Playgroud)


Jal*_*lil 6

实际上,你不需要一个有状态的组件来做你想做的事情(反模式:https://facebook.github.io/react/tips/props-in-getInitialState-as-anti-pattern.html).

相反,另一个更简单,更好的解决方案:

class MyComponent extends React.PureComponent {

    static propTypes = {            // <- This is not related to your question
        name: PropTypes.string,     //    but always declare your propTypes :-)
    }

    static defaultProps = {         // <- React provides defaultProps specifically
        name: 'Joseph Flowers',     //    for your use case !
    }
}
Run Code Online (Sandbox Code Playgroud)