【问题标题】:In React Router Dom, redirect not work if i don't press enter or refresh page在 React Router Dom 中,如果我不按 Enter 或刷新页面,重定向将不起作用
【发布时间】:2021-06-11 05:51:53
【问题描述】:

我对 React Router Dom 有一个奇怪的问题。 在我的代码中,我有:

if (this.state.area) {
return (<Redirect push to = {'/ service_list'} />)
}

在网址中正确写入“localhost:3000 / list_services,但似乎无法加载页面。如果我按回车键或重新加载页面,它会正确显示。有人可以帮助我吗? 在我的路线文件中,我有:

<Route exact path="/emilia_romagna">
  <Home/>
</Route>
<Route exact path="/lista_servizi">
  <ListaServizi/>
</Route>

【问题讨论】:

  • 您的路线匹配的是lista_servizi,而不是service_listlist_services
  • 你使用的是BrowserRouter还是Router
  • BrowserRouter 作为路由器
  • 您可以编辑您的代码以显示您“如何”导入和使用它吗?另外,您如何进行重定向?你是在你的类组件的render 函数中做的吗?如果它与history.push("/some/path") 一起工作,你可以试试吗?如果没有任何效果,请考虑创建一个 codepen 或 codesandbox 并向我们提供链接。

标签: javascript reactjs react-router react-router-dom react-router-component


【解决方案1】:

重写到这个模型:

import { BrowserRouter, Route } from "react-router-dom";

<BrowserRouter>
    <Route exact path="/emilia_romagna" component={Home} />
    <Route exact path="/lista_servizi" component={ListaServizi} />
    <Router component={NotFound} /> // Add this line and write the Not Found component to ensure that other paths mapped correctly.
</BrowserRouter>

【讨论】:

    猜你喜欢
    • 2017-12-15
    • 2021-07-27
    • 2019-01-05
    • 2021-07-24
    • 2021-02-11
    • 2018-05-21
    • 2019-07-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多