【问题标题】:How can I redirect via react router v4如何通过反应路由器 v4 重定向
【发布时间】:2019-06-22 06:17:18
【问题描述】:

基于isLoggedIn 我需要路由到不同的组件。

我正在获取登录页面,但无法呈现主页。

{this.state.isLoggedIn ?
    (
      <Route
        path='/home'
        render={() => <HomePage  onLogout={this.onLogout} />}
      />
    )
    :
    (
      <Route exact path='/' component={() => <LoginPage onLogin={this.onLogin} />}/>
    )
}

【问题讨论】:

    标签: reactjs react-router


    【解决方案1】:

    您可以使用this.props.history.push(myRoutes) 并在参数中发送路由。它会将您重定向到所需的路线。

    【讨论】:

      【解决方案2】:

      您可以通过呈现&lt;Redirect&gt; 来重定向将导航到新位置。新位置将覆盖历史堆栈中的当前位置,就像服务器端重定向 (HTTP 3xx) 一样。

      import { Route, Redirect } from 'react-router'
      
      <Route exact path="/" render={() => (
        loggedIn ? (
          <Redirect to="/dashboard"/>
        ) : (
          <PublicHomePage/>
        )
      )}/>
      

      用于通过重定向传递道具

      <Redirect to={{
          pathname: '/dashboard',
          state: { id: '123' }
      }} />
      

      然后你可以通过this.props.location.state.id访问prop

      【讨论】:

      • 如何将 props 发送到此重定向中的组件
      • 让我在答案中添加更多示例。 @ReNinja 我添加了通过重定向传递道具的示例。请检查
      • 在哪里可以指定组件名称 Homepage
      • 我想你可以看看这个教程blog.pshrmn.com/entry/simple-react-router-v4-tutorial有回报(
        );所以你可以为路由声明组件,并重定向到该路由
      • 重定向Line 36: Parsing error: Unexpected token, expected "," 34 | &lt;Redirect to={{ 35 | pathname: '/home', &gt; 36 | onLogout:{this.onLogout} | ^ 37 | }}/&gt; 38 | ) : ( 39 | &lt;LoginPage onLogin={this.onLogin} /&gt;时出现解析错误
      【解决方案3】:

      使用Redirect

      从您的父组件中,将 this.state.isLoggedIn 作为 props 传递给 LoginPage 和 HomePage 组件。

      在 LoginPage 组件中

      render(){
        if(this.props.isLoggedIn){
         return <Redirect to='/home' />
        }
      
        return ( your login page )
      }
      

      在 HomePage 组件中使用重定向路径 '/'代替。

      【讨论】:

      • 可以在 render() 函数中重定向吗?以及“”和“this.props.history.push('/home');”有什么区别
      • 抱歉回复晚了。是的,在渲染中重定向很好,因为 是一个反应的组件。这两者之间的区别在这里:stackoverflow.com/a/54452810/10104154
      猜你喜欢
      • 2018-10-24
      • 2017-08-10
      • 2016-11-22
      • 1970-01-01
      • 2017-10-21
      • 2017-12-06
      • 1970-01-01
      • 1970-01-01
      • 2017-09-16
      相关资源
      最近更新 更多