代码之家  ›  专栏  ›  技术社区  ›  bp123

React路由器重定向未重定向

  •  0
  • bp123  · 技术社区  · 7 年前

    handleSubmit(event) {
      event.preventDefault();
    
      if (isObjectEmpty(errorsInForm)) {
        Meteor.call(
          'user.multiplechoice.answer',
          conductedExamId,
          (err, res) => {
            if (err) {
              alert(err.reason);
            } else {
              <Redirect to="/test" />;
            }
          }
        );
      }
    }
    
    3 回复  |  直到 7 年前
        1
  •  3
  •   Rallen    7 年前

    <Redirect /> 是应该由 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 */
    }
    

    重定向 组件,只要想重定向,就必须访问 Router handleSubmit 使用 withRouter 允许它访问历史记录。

    import { withRouter } from "react-router";
    
    class MyAwesomeFormComponent {
        handleSubmit() {
            /* Call to api was successful */
            this.props.history.push("/test");
        }
    }
    
    export default withRouter(MyAwesomeFormComponent);
    
        2
  •  0
  •   Bankim Sutaria    7 年前

    带路由器 来自react路由器dom 然后使用这个.props.history.push(路由路径);