将数据从子级传递到父级React.js

时间:2018-07-08 00:44:32

标签: javascript reactjs react-redux

我正在尝试将数据从子组件传递到父组件。但是,这样做时出现错误:

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>

1 个答案:

答案 0 :(得分:2)

在渲染期间不允许调用setState,这将导致对props.callBackFromParent的调用。

您可以将该函数用作事件处理程序,它将按预期设置父级的状态。

示例

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

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