簡體   English   中英

將數據從子級傳遞到父級React.js

[英]Passing data from child to parent, React.js

我正在嘗試將數據從子組件傳遞到父組件。 但是,這樣做時出現錯誤:

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

我不明白,因為當我在事件處理程序中使用相同的模式時,一切都很好。 如何成功地將數據從子組件傳遞到父組件,而不會出現錯誤?

 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> 

不允許在渲染期間調用setStateprops.callBackFromParent將導致對props.callBackFromParent的調用。

您可以將該函數用作事件處理程序,它將按預期設置父級的狀態。

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM