Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

getChildContext() is called before getInitialState() #2929

Closed
andreypopp opened this issue Jan 24, 2015 · 2 comments
Closed

getChildContext() is called before getInitialState() #2929

andreypopp opened this issue Jan 24, 2015 · 2 comments

Comments

@andreypopp
Copy link
Contributor

I think it's a bug because it prevents child context from being dependent on component state.

var React = require('react');

var contextTypes = {
  name: React.PropTypes.string
};

class Test extends React.Component {

  getInitialState() {
    return {name: 'Name'};
  }

  getChildContext() {
    return {name: this.state.name};
  }

  render() {
    return <div />;
  }
}
Test.childContextTypes = contextTypes;

console.log(React.renderToString(<Test />));

Results in:

    return {name: this.state.name};
                            ^
TypeError: Cannot read property 'name' of null
    at Test.getChildContext ([stdin]:19082:29)
    at assign._processChildContext ([stdin]:6850:53)
    at assign._renderValidatedComponent ([stdin]:7249:33)
    at wrapper [as _renderValidatedComponent] ([stdin]:13368:21)
    at assign.mountComponent ([stdin]:6558:32)
    at wrapper [as mountComponent] ([stdin]:13368:21)
    at [stdin]:14177:27
    at ReactServerRenderingTransaction.Mixin.perform ([stdin]:16220:20)
    at Object.renderToString ([stdin]:14174:24)
    at Object.react ([stdin]:19092:19)
@gaearon
Copy link
Collaborator

gaearon commented Jan 24, 2015

This kept me curious for a while.

At what point does React read getChildContext?

If it references this.props and this.state, does that mean that context change has to propagate after componentDidUpdate, thus forcing reconciliation twice?

Somewhat related: #2517

@andreypopp
Copy link
Contributor Author

The correct way to define component state in terms of modern API:

var React = require('react');

var contextTypes = {
  name: React.PropTypes.string
};

class Test extends React.Component {

  constructor(props, context) {
    super(props, context);
    this.state = {name: 'Name!'};
  }

  getChildContext() {
    return {name: this.state.name};
  }

  render() {
    return <div />;
  }
}
Test.childContextTypes = contextTypes;

console.log(React.renderToString(<Test />));

Now that works, sorry.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants