简体   繁体   中英

Updating parent component from child component

I can't rerender the parent component from the child component - I pass componentDidMount as props to child class, then I call it there, and expect the parent to rerender. The render function is called, but the content remains unchanged. What's wrong?

var Parent = React.createClass({
   getInitialState: function () { return {content: 'clean'}; },
   componentDidMount: function () {
      this.setState({content: 'changed!'});
   },
   render: function () {
      return React.createElement('div', {rerender: this.componentDidMount.bind(this)}, this.state.content);
   }
});

var Child = React.createClass({
   render: function () {
      return React.createElement('div', {onClick: this.handleClick}, 'click me');
   },
   handleClick: function () {
      this.props.rerender();
   }
});

ReactDOM.render(
        React.createElement(ReactRouter.Router, {history: ReactRouter.browserHistory},
                React.createElement(ReactRouter.Route, {path: '/parent', component: Parent})
        )
, document.getElementById('content'));

componentDidMount() is a lifecycle function called when the component has completed rendering.

Calling it is seeming like you are circumventing the entire rerendering process.

You should instead create your own function.

   changeContent: function () {
      this.setState({content: 'changed!'});
   },

And then pass changeContent() to rerender .

Generally, avoid passing React's LifeCycle methods around!

To tackle all this kind of things, the guys at Facebook come up with unidirectional data flow pattern. Your child component should not know about the parent but rather it should change some sort of state (Flux, Redux, Reflux). Changes to the state will trigger rerendering of the parent component.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM