react-router问题:在地址栏中键入任何 url 重定向到 /

IT技术 reactjs react-router
2021-05-24 06:37:04

我的react-router有问题。如果我在地址栏中输入随机路由(mysite.com/users(用户页面的有效 url)或 mysite.com/adf(绝对无效的 url),应该显示 404page),路由器会将我重定向到主页('/' )。如果我点击在同一页面上的链接,一切都很好,必要的页面会显示出来。

  {
    path: '/',
    exact: true,
    cache: false,
    component: HomePage,
  },
  {
    path: '/users',
    exact: true,
    cache: false,
    component: UsersPage,
  },
  {
    path: '*',
    exact: true, // I tried both true and false
    cache: false,
    component: NotFoundPage,
    // also I tried to leave only component here
  },

然后我用renderRoutesfunc 从react-router-config

  <Switch location={location}>
    {renderRoutes(routes, { ...someParams })}
  </Switch>

我希望路由器不重定向我并显示所需页面,如果我输入地址栏有效 url,如 mysite.com/users 并显示未找到的页面,如果我输入地址栏无效 url,如 mysite.com/asd

UPD:问题仅在于 ConnectedRouter,如果我使用 react-router-dom 路由器,一切都很好

1个回答

所以问题出在 Switch 上。你不必使用它,因为 renderRoutes 有它自己的 Switch,你可以将 switch 参数作为第三个参数传递,比如{renderRoutes(routes, { ...someParams }, { ...switchParams })}