【问题标题】:react.js redirect inside functionreact.js 重定向内部函数
【发布时间】:2019-08-31 03:01:16
【问题描述】:

我正在尝试实现条件重定向。

所以在一个函数中我使用了这个:

if(request.responseText==="true"){
     window.location.href = '/home';
}
...

但是当我使用 react.js 时,我正在尝试从 react-router-dom 实现 Redirect

所以我尝试了这段代码:

if(request.responseText==="true"){
      <Router>
          <Redirect to={"/home"}/>
      </Router>
} 
...

但现在它甚至没有编译,它给了我错误:

期待一个赋值或函数调用,却看到一个表达式 no-unused-expressions

【问题讨论】:

    标签: reactjs react-router react-router-dom


    【解决方案1】:

    我想你不需要用Router 包裹它,你可以有这个,

    if(request.responseText==="true"){
       return <Redirect to="/home" />
    } 
    

    【讨论】:

      【解决方案2】:

      你的组件应该被包裹在 withRouter 中,参见React Router - withRouter,那么你的组件现在在 props 中有 history。在您的示例中,像这样使用它:

      if(request.responseText==="true"){
          this.props.history.push('/home')
      }
      

      希望这会有所帮助!快乐编码! :)

      【讨论】:

        【解决方案3】:

        根据文档应该是

         <Redirect to="/dashboard"/>
        

        请注意,大括号已被删除。

        https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/Redirect.md

        【讨论】:

          猜你喜欢
          • 2021-01-26
          • 2018-10-03
          • 1970-01-01
          • 2021-05-12
          • 2019-01-26
          • 2021-04-25
          • 1970-01-01
          • 2014-02-23
          • 1970-01-01
          相关资源
          最近更新 更多