简体   繁体   中英

Passing data from child to parent, React.js

I'm trying to pass data from a child component up to a parent component. However, when doing so, I get the error:

Warning: setState(...): Cannot update during an existing state transition (such as within render or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to componentWillMount

I don't understand because when I use the same pattern with an event handler, everything is fine. How can I successfully pass data from the child component to the parent without getting the error?

 const Child = (props) => { let message = 'Hi mom' props.callBackFromParent(message); return <h3>{props.message}</h3> }; class Parent extends React.Component { constructor(props){ super(props) this.state = { messageFromChild: '', } this.callBackFromParent = this.callBackFromParent.bind(this); } callBackFromParent(dataFromChild){ this.setState({messageFromChild: dataFromChild}) } render(){ return ( <div> <h2>Message from Child is:</h2> <Child message={this.state.messageFromChild} callBackFromParent={this.callBackFromParent} /> </div> ) } } ReactDOM.render( <Parent />, document.getElementById('root') ); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 

It's not allowed to call setState during rendering, which a call to props.callBackFromParent would result in.

You can use the function as an event handler instead, and it will set the state of the parent as expected.

Example

const Child = (props) => {
  let message = 'Hi mom';

  return <h3 onClick={() => props.callBackFromParent(message)}>{props.message}</h3>
};

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