我使用react和react-route進行身份驗證。 我的目標是:在菜單欄上react-route>登錄後重定向到請求的內容
- 登錄鏈接,用戶可以通過這個鏈接
- 登錄,如果用戶在隨後登錄我需要在頁面的頂部顯示不同的菜單結構
- 如果用戶刷新然後在瀏覽器的內容不同 菜單需要呈現,這取決於用戶 的狀態(登錄,或匿名用戶)
- 如果一個鏈接,是不公開的,然後登錄匿名用戶點擊表格需要自動顯示 需要
- 成功登錄過程後,用戶被重定向到所請求的內容
我的解決辦法工作正常(如果有人有興趣的話,我會在這裏發佈我的代碼)。 (5)。我有一個與我最後一個目標有關的問題,(5)。我不知道在圖層中發送原始請求的路徑信息的最佳做法是什麼。最初請求的路徑出現在App.js(Route)中。然後它需要傳遞給onEnter方法。如果它是一個匿名用戶,而不是所請求的路徑需要傳遞給顯示的Login組件,並且最終在成功登錄後需要對原始請求的路由進行重定向。
我的解決方案使用url參數將請求的原始路由信息傳遞給登錄組件。
這裏是我的代碼:
App.js
function requireAuth(nextState, replace) {
if (!auth.loggedIn())
replace({
pathname: '/login?route=' + nextState.location.pathname,
state: { nextPathname: nextState.location.pathname }
})
}
ReactDom.render(
<Router history={hashHistory} onUpdate={() => window.scrollTo(0, 0)}>
<Route path="/" component={MainLayout}>
<IndexRoute component={Home} />
<Route path="login" component={Login} />
<Route path="login?route=:route" component={Login} />
<Route path="logout" component={Logout} />
<Route path="about" component={About} />
<Route path="profile" component={Profile} onEnter={requireAuth} />
</Route>
</Router>,
document.getElementById('root')
);
Login.js
import React from 'react';
import { withRouter } from 'react-router';
import auth from '../auth/Auth';
import Button from "react-bootstrap/lib/Button";
export default class Login extends React.Component {
doRedirect() {
if (this.props.location.query.route)
this.props.router.push(this.props.location.query.route);
else
this.props.router.push('/');
}
render() {
return (
<div style={style.text}>
<h3>LOGIN FORM</h3>
<Button bsStyle="primary" onClick={() => auth.login("username", "password", this.doRedirect.bind(this))}>
Login
</Button>
</div>
);
}
}
// wrap with the withRouter HoC to inject router to the props, instead of using context
export default withRouter(Login);
有沒有更好或更符合反應液通過請求的URI來登錄組件?
THX。
只有一個改善我能做些什麼:更換({ 路徑: '/登錄', 查詢:{路線:nextState。location.pathname}, state:{nextPathname:nextState.location.pathname} }) – zappee