我正在尝试实现重定向到登录页面,然后在成功登录后重定向到个人资料页面。
当我这样做
import { Router } from 'react-router-dom';
重定向到登录页面无效。但是,如果我使用BrowserRouter,它会起作用:
import { BrowserRouter as Router } from 'react-router-dom';
根据快速搜索的信息,浏览器路由器无法与histry.push
配合使用,登录成功后我需要使用它。
我做错了什么?
历史记录:
import { createBrowserHistory } from 'history';
const history = createBrowserHistory();
export default history;
App.js:
//...
import { Router, Route, Switch } from 'react-router-dom'; // redirects if using BrowserRouter as Router
import history from './helpers/history';
//...
function App() {
return (
<div className="App">
<Router history={history}>
<Switch>
<PrivateRoute exact path={process.env.REACT_APP_ROUTE_PREFIX} component={ProfilePage} />
<Route path={`${process.env.REACT_APP_ROUTE_PREFIX}/login`} component={LoginPage} />
</Switch>
</Router>
</div>
);
}
export default App;
index.js:
// ...
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById('root')
);
PrivateRoute.jsx:
import React from 'react';
import { Route, Redirect, withRouter } from 'react-router-dom';
const PrivateRoute = withRouter(({ component: Component, ...rest }) => (
<Route {...rest} render={props => (
localStorage.getItem('user')
? <Component {...props} />
: <Redirect to={{ pathname: `${process.env.REACT_APP_ROUTE_PREFIX}/login`,
state: { from: props.location } }} />
)} />
))
登录后:
import history from '../../helpers/history'
//...
// thunk
export const login = (username, password) => dispatch => {
dispatch(request({ username }));
authClient.login(username, password)
.then(
user => {
dispatch(success(user));
// updates the url, but doesn't get caught by BrowserRouter
// useHistory doesn't work here as it's for stateless components
history.push(process.env.REACT_APP_ROUTE_PREFIX);
},
error => {
dispatch(failure(error));
}
);
}
模块版本:
"history": "^5.0.0",
"react-router-dom": "^5.2.0",
LoginPage
和ProfilePage
也用withRouter
答案 0 :(得分:0)
好的,我通过使用LoginPage属性中的历史记录解决了此问题:
export const login = (username, password, history) => dispatch => {
//...
history.push(process.env.REACT_APP_ROUTE_PREFIX);
//...
}
handleSubmit(e) {
e.preventDefault();
this.setState({ submitted: true });
const { username, password } = this.state;
const { dispatch, history } = this.props;
if (username && password) {
dispatch(login(username, password, history));
}
}
我不确定这是否是一个好方法。有人可以建议吗?