什么是反应路由器onEnter nextPathname在做什么?

时间:2016-05-02 19:18:46

标签: reactjs react-router

在下面的代码中,如果不是auth,则重定向到使用replace pathname登录,但state做什么?

EDITED onEnter不会将用户重定向到同一位置

login.js

    login() {

/*      ref.authWithOAuthPopup(this.props.provider, (error, authData) => {
            if (error) {
                console.log("Authentication Failed!", error);
            } else {
                console.log("Authenticated successfully with payload:", authData);
                console.log(this.state) // return null here
            }
        }) */
    }

authenticated.js

import Firebase from 'firebase';
import GLOBAL from './global.js';

var ref = new Firebase(GLOBAL.FIREBASE_URL);

export function requireAuth(nextState, replace) {

    ref.onAuth((authData) => {
        if ( !authData ) {
            replace ({
                pathname: '/login',
                state: { nextPathname: nextState.location.pathname }
            })
        }
    })
}

route.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, browserHistory, hashHistory, IndexRoute } from 'react-router';
import Layout from './pages/Layout';
import Purchased from './pages/Purchased';
import Home from './pages/Home';
import Profile from './pages/Profile';
import PurchasedItemDetail from './pages/PurchasedItemDetail';
import Login from './pages/Login';
import { requireAuth } from './utils/authenticated';

ReactDOM.render((
  <Router history={browserHistory}>
    <Route path="/" component={Layout}>
        <IndexRoute component={Home} onEnter={requireAuth} />
        <Route path="/login" component={Login} />
        <Route path="/purchased" component={Purchased} onEnter={requireAuth} />
        <Route path="/purchased/:purchasedItemID" component={PurchasedItemDetail} onEnter={requireAuth} />
        <Route path="/profile" component={Profile} onEnter={requireAuth} />
    </Route>
  </Router>
), document.getElementById('app')) 

1 个答案:

答案 0 :(得分:0)

此函数中的nextState参数是Router State object,表示用户将要进入的应用程序的下一个状态。因此,当您传递state: { nextPathname: nextState.location.pathname }时,您正在告诉路由处理程序您希望发送此数据。在这种情况下,它基本上是一个重定向路线。登录后Aka将它们重定向到某个位置。