How to set states with details in response.js ES6

I would like to know how to set my states with props using ES6

Before:

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

And now I'm trying to do this, but this.propsdoes not exist:

class MyComponent extends React.Component {
  constructor() {
    super()
      this.state = { name: this.props.name || 'Joseph Flowers' };
  }
}
+4
source share
4 answers

Actually you do not need the statefull component for what you are trying to do (anti-pattern: https://facebook.imtqy.com/react/tips/props-in-getInitialState-as-anti-pattern.html ).

Instead, another simpler, better solution:

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 !
    }
}
+6
source

You just need to pass the attribute parameter in the constructor method:

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

Please note that in some cases this is not an anti-pattern:

( .)

, -, , , : : https://facebook.imtqy.com/react/tips/props-in-getInitialState-as-anti-pattern.html

BTW 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'));
+6

const MyComponent = (props) => {
 return <div>Hi {props.name || 'Joseph Flowers'}! </div>
}
+1

es7 .

class App extends React.Component {
    static propTypes = {
        title: React.PropTypes.string.isRequired,
    }   

    // or pass from parent Componet 
    static defaultProps = {
        title: 'hello',
    }

    state = {
        title: this.props.title
    }
    // ...
}
0

Source: https://habr.com/ru/post/1654528/


All Articles