history.push 仅在 React 应用程序中使用 BrowserRouter 时更新 URL
history.push only updates the URL when using BrowserRouter in react application
我知道这个问题之前已经讨论过了。但是,不知何故我无法在我的应用程序中使用它。
通常情况下,组件之间的导航工作正常。但是,history.push 仅更改 url 而不会更新内容。例如,在登录页面中,如果已经登录,我想将用户导航到主页。但是,代码只更新 url。有什么想法吗?
const Login = () => {
useEffect(() => {
if (authenticationService.currentUserValue != null) {
history.push('/home');
}
}, [])
//other code
}
在index.js中,我有以下
<BrowserRouter basename={baseUrl} history={history}>
<Provider store={store}>
<App />
</Provider>
</BrowserRouter >,
在app.js中,我有:
<Layout>
<Switch>
<PrivateRoute exact path="/home" component={withRouter(Home)} />
<Route exact path='/home' component={withRouter(Home)} />
<Route exact path='/login' component={Login} />
<Route exact path='/register' component={withRouter(Register)} />
</Switch>
</Layout>
您遇到的问题是您使用的 BrowserRouter 自定义历史记录不正确。 BrowserRouter 使用自己的历史记录,您必须使用它来更改页面
const Login = ({history}) => {
useEffect(() => {
if (authenticationService.currentUserValue != null) {
history.push('/home');
}
}, [])
//other code
}
如果您出于某种原因使用了自定义历史记录,那么您需要将 Router
与自定义历史记录道具一起使用
<Router basename={baseUrl} history={history}>
<Provider store={store}>
<App />
</Provider>
</Router >
我知道这个问题之前已经讨论过了。但是,不知何故我无法在我的应用程序中使用它。
通常情况下,组件之间的导航工作正常。但是,history.push 仅更改 url 而不会更新内容。例如,在登录页面中,如果已经登录,我想将用户导航到主页。但是,代码只更新 url。有什么想法吗?
const Login = () => {
useEffect(() => {
if (authenticationService.currentUserValue != null) {
history.push('/home');
}
}, [])
//other code
}
在index.js中,我有以下
<BrowserRouter basename={baseUrl} history={history}>
<Provider store={store}>
<App />
</Provider>
</BrowserRouter >,
在app.js中,我有:
<Layout>
<Switch>
<PrivateRoute exact path="/home" component={withRouter(Home)} />
<Route exact path='/home' component={withRouter(Home)} />
<Route exact path='/login' component={Login} />
<Route exact path='/register' component={withRouter(Register)} />
</Switch>
</Layout>
您遇到的问题是您使用的 BrowserRouter 自定义历史记录不正确。 BrowserRouter 使用自己的历史记录,您必须使用它来更改页面
const Login = ({history}) => {
useEffect(() => {
if (authenticationService.currentUserValue != null) {
history.push('/home');
}
}, [])
//other code
}
如果您出于某种原因使用了自定义历史记录,那么您需要将 Router
与自定义历史记录道具一起使用
<Router basename={baseUrl} history={history}>
<Provider store={store}>
<App />
</Provider>
</Router >