反应路由器问题:在地址栏中键入任何 url 重定向到/ [英] React router issue: typing any url in address bar redirects to /

查看:54
本文介绍了反应路由器问题:在地址栏中键入任何 url 重定向到/的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm having an issue with react-router. If I type random route in address bar (mysite.com/users (valid url to users page) or mysite.com/adf (definitely not valid url), which should show 404page), router redirects me to home page ('/'). If I click on Link which leads on same page, everything is fine, the necessary page is shown.

  {
    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
  },

然后我使用 react-router-config

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

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

I want router not to redirect me and show needed page if I type in address bar valid url, like mysite.com/users and to show not found page, if I type in address bar invalid url, like mysite.com/asd

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

UPD: The problem is only with ConnectedRouter, if I use react-router-dom Router everything is fine

推荐答案

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

So the issue was in Switch. You don't have to use it, because renderRoutes has it's own Switch and you can pass switch params as third argument, like {renderRoutes(routes, { ...someParams }, { ...switchParams })}

这篇关于反应路由器问题:在地址栏中键入任何 url 重定向到/的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆