【问题标题】:Page not found in nested Routes在嵌套路由中找不到页面
【发布时间】:2020-08-31 18:56:35
【问题描述】:

我正在尝试在我的应用中设置一些嵌套路由,但由于某种原因,我无法让它打开我的嵌套页面。

在 index.js 中

<Router>
  <Switch>
    <Route exact path="/" component={App}/>
    <Route path="/admin" component={AdminApp}/>
    <Route component={() => { return <div>Page not found</div>}}/>
  </Switch>
</Router>

在 AdminApp.jsx 中:

import ViewUser from "./ViewUser";

export default function AdminApp({ match }) {
    const [users, setUsers] = useState([]);

    useEffect(() => {...axios to get users from db and setUsers()...}, [])

    return (
    <>
      <div>User</div>
      <Link to={`${match.url}/users/view/${user.Name}`>View</Link>
      <Switch>
        <Route path={`${match.path}/users/view/:username`} component={ViewUser}/>
      </Switch>
    </>) 
}

ViewUser 组件是AdminApp 组件的子组件。

每当我点击 View 链接时,它都会将我的 url 更改为 http://localhost:3001/admin/users/view/theusernameoftheselecteduser ,因此 url 本身(至少在浏览器栏中)是正确的,但它呈现 Page not found 路由,它从不呈现 ViewUser 组件。我里面有一个console.log,它根本不会被触发。

编辑:这个问题的公认答案是我正在尝试做的Nested routes with react router v4 / v5,但由于某种原因我无法让它工作。

https://reactrouter.com/web/example/nesting react-router 的相同示例,我无法让它工作

【问题讨论】:

    标签: reactjs react-router


    【解决方案1】:

    您的应用程序将始终呈现一个切换路由。当不匹配任何内容时,它将呈现未找到的页面。

    将路由添加为 Switch 的子路由,然后当路径匹配时,它将呈现组件而不是“未找到”

    <Router>
      <Switch>
        <Route exact path="/" component={App}/>
        <Route exact path="/admin" component={AdminApp}/>
        <Route path={`/admin/users/view/:username`} component={ViewUser}/>
        <Route component={() => { return <div>Page not found</div>}}/>
      </Switch>
    </Router>
    

    【讨论】:

    • ViewUser 是一个组件,它是 AdminApp 组件的子组件,这就是我尝试嵌套路由的原因。如果我有 1000 条不同的路由,我应该将它们全部添加到 index.js 的主路由中吗?好像不对。
    • 那么,在/admin/users/view/:username这个路径上,你只想渲染viewUser而不渲染AdminApp??
    • 没错,View 链接在 AdminApp 内部,我应该从那里渲染 ViewUser 组件
    • 一个问题是您的 Switch 中有一个“默认”语句。因此,如果没有匹配项,它将呈现未找到。
    • 我想不出除了在 switch 中添加路由之外的其他方法
    【解决方案2】:

    从您的管理路由中删除 exact 属性。使用 exact 属性集,无法匹配 /admin 之后的任何内容。

    【讨论】:

    • 好的,我这样做了,但是现在,当我单击查看链接时,它会更改我在浏览器上的 URL,但只会呈现 /admin 组件
    猜你喜欢
    • 2019-02-15
    • 1970-01-01
    • 1970-01-01
    • 2022-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-02
    相关资源
    最近更新 更多