Reactjs history.push仅在react应用程序中使用BrowserRouter时更新URL

Reactjs history.push仅在react应用程序中使用BrowserRouter时更新URL,reactjs,react-router,browser-history,Reactjs,React Router,Browser History,我知道这个问题以前已经讨论过了。但是,不知何故,我无法让它在我的应用程序中工作 通常,组件之间的导航工作正常。但是,history.push仅更改url,而不更新内容。例如,在登录页面中,如果用户已经登录,我希望将其导航到主页。但是,代码只更新url。有什么想法吗 const Login = () => { useEffect(() => { if (authenticationService.currentUserValue != null) {

我知道这个问题以前已经讨论过了。但是,不知何故,我无法让它在我的应用程序中工作

通常,组件之间的导航工作正常。但是,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 >


尝试将应用程序组件呈现为默认路由。此外,您不需要与路由器一起使用components@ShubhamKhatri谢谢你的评论。请您帮助我理解将应用程序组件呈现为默认路由是什么意思?@ShubhamKhatri这会使页面崩溃。将
浏览器路由器
更改为
路由器
解决了问题。但是,如果我想使用
浏览器路由器
?还是我应该?