React-router4 第三篇 BasicURL ParametersRedirects (Auth) 谷歌翻譯:重定向


依舊是地址
https://reacttraining.com/react-router/web/example/auth-workflow

上來一步走 先導入模塊

import React, { PropTypes } from 'react'
import {
  BrowserRouter as Router,
  Route,
  Link,
  Redirect,
  withRouter
} from 'react-router-dom'

關鍵組件

<Redirect to={{ pathname: "/path", other: "" }}/>

官方代碼

const AuthExample = () => (
  <Router>
    <div>
      <AuthButton/>
      <ul>    // 同樣,先定義a標簽
        <li><Link to="/public">Public Page</Link></li>
        <li><Link to="/protected">Protected Page</Link></li>
      </ul>
      // 再定義路由  兩個看似很普通的路由,和一個不那么普通的路由,,官方例子中,點擊/protected路由,卻發現地址欄訪問了login路由。。
      <Route path="/public" component={Public}/>
      <Route path="/login" component={Login}/>
      <PrivateRoute path="/protected" component={Protected}/> // 原來這里確實訪問了/protected 但是卻在<PrivateRoute />組件中又被跳走了
    </div>
  </Router>
)

關鍵代碼 在這里!!!
ES6的 ...rest 的展開運算符,,很囂張,很暴力!,不懂的話,百度ES6 展開運算符,,在這里...rest 指代的是 path="/protected"

const PrivateRoute = ({ component, ...rest }) => (
  <Route {...rest} render={props => (
    fakeAuth.isAuthenticated ? (
      React.createElement(component, props)
    ) : (
      <Redirect to={{            // 重定向組件來了,,Redirect是也。!! 然后傳參給pathname,,然后就重定向走了呀。。。順便可以加點參數什么的,另一頭就可以接受=收了
        pathname: '/login',
        state: { from: props.location }
      }}/>
    )
  )}/>
)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM