我正在使用firebase登录/注册React Router v4。 在登录/注册到其他组件后,我可以使用什么来代替browserHistory来重定向用户?
那么使用什么
browserHistory.push('/app');
。我尝试了<Redirect push to="/app" />
而browserHistory.replace('/signin');
我尝试了<Redirect replace to="/signin" />
但它不起作用。
以下是代码的一部分: import和onAuthStateChanged()函数
import React from 'react';
import ReactDOM from 'react-dom';
import { Switch, Redirect, Route} from 'react-router';
import { BrowserRouter, Link } from 'react-router-dom';
import { firebaseApp } from './firebase';
firebaseApp.auth().onAuthStateChanged(user => {
if(user) {
console.log('user has singed in or up', user);
//**** WHAT TO USE INSTEAD OF THIS?*******
// browserHistory.push('/app');
}
else {
console.log('user has signed out or still needs to sign in');
//**** WHAT TO USE INSTEAD OF THIS?*******
// browserHistory.replace('/signin');
}
})
答案 0 :(得分:1)
browserHistory已不在react-router-v4
最好的方法是使用withRouter
HOC,然后您就可以访问历史道具。从技术上讲,你可以通过上下文访问它,但我不鼓励它。
import React from 'react';
import ReactDOM from 'react-dom';
import { Switch, Redirect, Route} from 'react-router';
import { BrowserRouter, Link, withRouter } from 'react-router-dom';
import { firebaseApp } from './firebase';
firebaseApp.auth().onAuthStateChanged(user => {
if(user) {
console.log('user has singed in or up', user);
//**** WHAT TO USE INSTEAD OF THIS?*******
// browserHistory.push('/app');
this.props.history.push('/app')
}
else {
console.log('user has signed out or still needs to sign in');
//**** WHAT TO USE INSTEAD OF THIS?*******
// browserHistory.replace('/signin');
this.props.history.push('/signin')
}
})
export withRouter(yourComponent)
答案 1 :(得分:0)
另一种解决方案是:
import createHistory from 'history/createBrowserHistory';
然后创建const历史记录:
const history = createHistory();
firebaseApp.auth().onAuthStateChanged(user => {
if(user) {
const { email } = user;
history.push('/');
}
else {
history.replace('/signin');
}
})
然后在
上调用历史记录 <Router history={history}>