如果我的 React 应用程序登录成功,我会尝试将用户重定向到新页面。重定向是从身份验证服务调用的,该服务不是组件。为了访问组件外的历史对象,我遵循了React Router FAQ中的这个例子。但是,当我调用 时history.push('/pageafterlogin'),页面没有改变,我仍然停留在登录页面上(基于我Switch希望最终出现在404页面上)。地址栏中的 URL 确实更改为,/pageafterlogin但该页面未从登录页面更改。控制台或其他任何内容中都没有出现错误以表明我的代码不起作用。
我怎样才能history.push()改变用户所在的页面?
// /src/history.js
import { createBrowserHistory } from 'history';
export default createBrowserHistory();
// /src/App.js
...
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import history from './history';
function App() {
return (
<Router history={history}>
<Switch>
<Route path="/" exact component={HomePage} />
<Route path="/login" exact render={() => <FormWrapper><LoginForm /></FormWrapper>} />
<Route render={() => <h1>404: not found</h1>} />
</Switch>
</Router>
);
}
export default App;
// src/services/auth.service.js
import axios from 'axios';
import history from '../history';
const API_URL = '...';
class AuthService {
login(username, password) {
return axios.post(API_URL + 'login', {
username,
password
}).then(res => {
if (res.status === 200) {
localStorage.setItem('user', JSON.stringify(res.data));
history.push('/pageafterlogin');
}
});
}
}