本文介绍了在React Router V4中重定向经过身份验证的用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用react js和firebase创建一个简单的登录应用程序
I create a simple login application using react js and firebase
当我注册它会在firebase中创建一个用户时,我需要将auth用户重定向到我的Index.js文件的另一页,如下所示
when I sign up it will create a user in firebase I need to ridirect auth user to another page my Index.js file like below
import React from 'react';
import ReactDOM from 'react-dom';
import { firebaseApp } from './firebase'
import { BrowserRouter as Router, Route, Redirect } from 'react-router-dom';
import App from './components/App';
import Signin from './components/Signin';
import Signup from './components/Signup';
firebaseApp.auth().onAuthStateChanged(user => {
if(user) {
console.log('user has signed in or up', user);
return <Redirect to='/dashboard'/>;
} else {
console.log('user signed out or still need to sign in', user);
// browserHistory.replcae('/signin')
return <Redirect to='/signin'/>;
}
})
ReactDOM.render(
<Router path="/">
<div>
<Route path="/dashboard" component={App} />
<Route path="/signup" component={Signup} />
<Route path="/signin" component={Signin} />
</div>
</Router>, document.getElementById('root')
);
我做错了什么,请帮助我,我是新来的
What did I do wrong please help me Im new to react
推荐答案
您需要为路由器创建一个组件,然后在该组件中调用逻辑.用这样的类替换自由浮动的firebaseApp函数...
You need to create a component for your router and call your logic in that component. Replace your free-floating firebaseApp function with a class like so...
class Routes extends React.Component {
componentDidMount() {
firebaseApp.auth().onAuthStateChanged(user => {
if(user) {
console.log('user has signed in or up', user);
return <Redirect to='/dashboard'/>;
} else {
console.log('user signed out or still need to sign in', user);
// browserHistory.replcae('/signin')
return <Redirect to='/signin'/>;
}
})
}
render() {
return (
<div>
<Route path="/dashboard" component={App} />
<Route path="/signup" component={Signup} />
<Route path="/signin" component={Signin} />
</div>)
}
}
然后您可以像这样...在ReactDOM.render中引用此组件...
Then you can reference this component in ReactDOM.render like so...
ReactDOM.render(
<Router>
<Routes>
</Router>, document.getElementById('root')
);
这篇关于在React Router V4中重定向经过身份验证的用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!