如何根据"react-router": "^4.0.0"
中的条件重定向到特定页面。
var { HashRouter, Route, Switch} = require('react-router-dom');
var {Provider} = require('react-redux');
firebase.auth().onAuthStateChanged((user) => {
if (user){
this.props.history.push('/todos/');
}else{
this.props.history.push('/');
}
});
store.dispatch(actions.startAddTodos());
ReactDOM.render(
<Provider store = {store}>
<div>
<HashRouter>
<div>
<div className="columns medium-6 large-4 small-centered">
<Switch>
<Route path='/todos' component={TodoApp}/>
<Route path='/login' component={Login}/>
<Route component={Login}/>
</Switch>
</div>
</div>
</HashRouter>
</div>
</Provider>,
document.getElementById('app')
);
无法阅读属性&#39;道具&#39;未定义的
编辑:
Github上的应用程序: React-Todo
答案 0 :(得分:8)
您不能使用this.props
,因为您不在组件内部。
因此,要执行重定向,您需要使用Redirect
react-router-dom
组件
我建议您创建一个HOC(高阶组件来处理它。
import React from 'react'
import { Redirect, Route } from 'react-router-dom'
import firebase from 'firebase'
const PrivateRoute = ({ component: Component, ...rest }) => {
return(
<Route {...rest} render={props => (
firebase.auth().onAuthStateChanged((user) => user
?(
<Component />
)
:(
<Redirect to={{
pathname: '/login',
state: { from: props.location }
}}/>
)
)
)}/>
)
}
export default PrivateRoute
然后,您只需要在index.js文件中导入PrivateRoute,而不是使用Route
使用PrivateRoute
作为需要进行身份验证的路由。
var { HashRouter, Route, Switch} = require('react-router-dom');
var PrivateRoute = require('./privateRoute')
var { Provider } = require('react-redux');
store.dispatch(actions.startAddTodos());
ReactDOM.render(
<Provider store = {store}>
<div>
<HashRouter>
<div>
<div className="columns medium-6 large-4 small-centered">
<Switch>
<PrivateRoute path='/todos' component={TodoApp}/>
<Route path='/login' component={Login}/>
<Route component={Login}/>
</Switch>
</div>
</div>
</HashRouter>
</div>
</Provider>,
document.getElementById('app')
);
答案 1 :(得分:1)
如果您正在使用反应路由器,那么在您所在州维持用户身份验证时可能会更容易。
{ /* Protect your routes you can include any no.of routes */ }
<Route onEnter={requireLogin}>
<Route path='/todos' component={TodoApp}/>
</Route>
接下来,为requireLogin编写一个小包装器,在其中检查auth状态并在其中进行重定向。它看起来像这样
const requireLogin = (nextState, replace, cb) => {
function checkAuth() {
const user = firebase.auth().onAuthStateChanged(user => user); // check login in your state
if (!user) {
replace('/'); // make user to redirect to some route based on your requirement
}
cb(); //if user present in it fallback to here
}
};