3

I want to seed my component state using data from my props like the example here: https://facebook.github.io/react/tips/props-in-getInitialState-as-anti-pattern.html

getInitialState: function() {
    return {count: this.props.initialCount};
},

Look near the bottom where it says "However, it's not an anti-pattern if you make it clear that the prop is only seed data for the component's internally-controlled state:" That is exactly what I want to do.

This works great when using React.createClass, but I'd like to do this using ES6 classes if possible. But when using ES6 classes, initial state is provided as a static property on the class. If you try to implement getInitialState(), you'll get an error. This means that I don't get the opportunity to compute it after props are available. See the section titled "ES7+ Property Initializers" at https://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#es7-property-initializers

In that section, they provide an example where the initial state is computed similar to the old getInitialState method, by simple setting this.state in the constructor. However, when I tried this, this.props was not set yet.

I have searched for a lifecycle method for when the props are initially set for the first time so that I can set the state at that moment, but I can't find any such lifecycle method.

Must I use React.createClass or is there a way to seed my initialState when using ES6 classes extending React.Component?

Dustin
  • 2,091
  • 3
  • 15
  • 13

3 Answers3

1

It turns out I wasn't passing arguments to super in my constructor which is why the props weren't available in the constructor. I just had to change this:

constructor() {
  super()
  ...
}

into this:

constructor(...args) {
  super(...args)
  ...
}

My question was very similar to How to assign a prop value to a state in react which is what tipped me off to my mistake, so this might be considered a duplicate.

Community
  • 1
  • 1
Dustin
  • 2,091
  • 3
  • 15
  • 13
1

Here is a sample class where you can get it working

class Sample extends React.Component {
  constructor(props, context) {
    super(props, context);

    // replacement for componentWillMount
    this.state = {
      stateKey: props.stateVal
    };
  }

  render() {
    return (
      <div>{this.state.stateKey}</div>
    );
  }
}
psiyumm
  • 6,437
  • 3
  • 29
  • 50
  • 1
    `this.props` is undefined in the constructor. you want to get the value from the `props` arg directly: `stateKey: props.stateVal` – rossipedia Mar 27 '16 at 03:10
0
  class Sample extends React.Component {
    constructor(props, context) {
        super(props, context);
         this.state = {
               stateKey: ''
          };
       }

       componentWillReceiveProps(){
        this.setState({
           stateKey:this.props.data
         })

       render() {
          return (
           <div>{this.state.stateKey}</div>
       );
    }

}

SM Chinna
  • 341
  • 2
  • 7