【问题标题】:React Router Redirect is not redirectingReact Router Redirect没有重定向
【发布时间】:2019-10-02 05:07:06
【问题描述】:

我在提交表单后尝试重定向离开此页面。出于某种原因,它什么也没做。我没有收到错误,页面保持不变。我正在使用反应路由器 4。我在这里缺少什么?

handleSubmit(event) {
  event.preventDefault();

  if (isObjectEmpty(errorsInForm)) {
    Meteor.call(
      'user.multiplechoice.answer',
      conductedExamId,
      (err, res) => {
        if (err) {
          alert(err.reason);
        } else {
          <Redirect to="/test" />;
        }
      }
    );
  }
}

【问题讨论】:

  • 而不是使用 尝试使用 `this.props.history.push('/test') '
  • 您应该在渲染方法中返回 。在内部方法中,您可以使用 props 中的历史来推送。
  • @tarzenchugh 人,非常感谢!我面临这个问题一个星期。你解释了我以前没有找到的东西。再次感谢您

标签: reactjs meteor react-router-v4


【解决方案1】:

&lt;Redirect /&gt; 是一个组件,应该由render 函数返回,而不是在事件处理程序中。如果你想使用Redirect组件,你必须在你的api调用成功时设置一个状态,并根据该状态渲染组件。

state = {
    formSuccess: false
}

handleSubmit(event) {
    /* Call to api was successful */
    this.setState({ formSuccess: true });
}

render() {
    if (this.state.formSuccess) {
        return (<Redirect to="/test" />);
    }

    /* The rest of your render function */
}

如果您不想使用Redirect 组件而只想重定向,则必须有权访问Router 组件的历史记录。为此,您可以使用 withRouter HOC 包装具有 handleSubmit 函数的组件,以使其能够访问历史记录。

import { withRouter } from "react-router";

class MyAwesomeFormComponent {
    handleSubmit() {
        /* Call to api was successful */
        this.props.history.push("/test");
    }
}

export default withRouter(MyAwesomeFormComponent);

【讨论】:

    【解决方案2】:

    首先使用来自 react-router-dom 的高阶组件 withRouter ''' 然后使用 this.props.history.push(“route-path”); '''

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-22
      • 2017-11-14
      • 1970-01-01
      • 2022-06-17
      • 1970-01-01
      • 1970-01-01
      • 2017-11-15
      • 1970-01-01
      相关资源
      最近更新 更多