【问题标题】:history.push only updates the URL when using BrowserRouter in react applicationhistory.push 仅在 react 应用程序中使用 BrowserRouter 时更新 URL
【发布时间】:2019-09-21 06:01:29
【问题描述】:

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

通常,组件之间的导航可以正常工作。然而,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>

【问题讨论】:

  • 尝试将您的 App 组件渲染为默认路由。此外,您不需要将 withRouter 与组件一起使用
  • @ShubhamKhatri 感谢您的评论。你能帮我理解rendering your App component as a default Route是什么意思吗?
  • @ShubhamKhatri 这会使页面崩溃。
  • BrowserRouter 更改为Router 解决了这个问题。但是,如果我想使用BrowserRouter 怎么办?还是应该?

标签: reactjs react-router browser-history


【解决方案1】:

您的问题是您使用 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 >

【讨论】:

    猜你喜欢
    • 2021-10-03
    • 2017-02-23
    • 2021-09-20
    • 1970-01-01
    • 2019-05-13
    • 2019-08-21
    • 2018-01-21
    • 2021-06-26
    • 2020-05-21
    相关资源
    最近更新 更多