如果从子组件调用,则this.props.history未定义

时间:2018-03-09 12:09:12

标签: reactjs react-router react-props

我正在尝试从父组件内部验证答案。 validateAnswer函数被触发,几乎可以正常工作。

但我想更改网站,如果它已经过验证。所以我从父母那里打电话给this.props.history.push。 这给了我一个错误,因为历史是未定义的。

<Answers handleClick={e => this.validateAnswer(e)} />

//Function to validate the Answer in the parent
    validateAnswer = (event) => {
    if (true) {
      //navigate to /email
      this.props.history.push({
        pathname: '/email',
        state: { lastPage: 'question' },
      });

    //Child component
         <Button
          name="1"
          label="Afrika"
          handleClick={props.handleClick}
        />

我该如何解决这个问题?我应该直接在答案组件中验证答案吗?

1 个答案:

答案 0 :(得分:0)

试试这个:

<Answers handleClick={this.validateAnswer} />

// Function to validate the Answer in the parent
validateAnswer(event){
if (true) {
  //navigate to /email
  this.props.history.push({
    pathname: '/email',
    state: { lastPage: 'question' },
  });

// Child component
 <Button
  name="1"
  label="Afrika"
  handleClick={(e) => props.handleClick(e) }
/>