react-router 一些路由不匹配

react-router some routes not matching

我有私有路由

app-routes.js文件

const routes = [
{ path: '/', component: HomePage },
{ path: '/articles/:id', component: Article },
{ path: '/expert', component: Experts },
...
{ path: '/requests', component: ComRequest },
{ path: '/admin', component: AdminHomePage },]

export default routes.map(route => {
 return {
  ...route,
  component: route.component
 }
})

content.js 文件将应用程序路由迭代为数组 如果不匹配任何路由重定向到 /

import routes from 'app-routes'

return(
 <Switch>
  {routes.map(({ path, component }) => (
    <PrivateRoute
     exact
     key={path}
     path={path}
     component={component}
    />
   ))}
  <Redirect to={'/'} />
 </Switch>)

PrivateRoute.js 组件文件检查用户是否重定向到 /login

function PrivateRoute({ component, ...rest }) {
 return (
  <Switch>
   <Route
    {...rest}
    render={(matchProps) => getUser()
     ?
      <WithLayout
       {...matchProps}
       component={component}
       layout={MainLayout}
      />
      :
      <Redirect to={{ pathname: '/login', state: { from: matchProps.location } }} />}
   />
  </Switch>
 )
}

export default PrivateRoute

getUser()函数returns对象字符串{userdata}

getUser.js

export function getUser() {
 return localStorage.getItem('user')
}

在浏览器中,一些 /articles/expert 路由呈现视图,但随机或逻辑无法弄清楚其他一些 /requests, /admin 路由不匹配并重定向到 /

有时每个路由都重定向到 /

如果我评论<Redirect to={'/'}/>一些路由呈现白屏

还有一件烦人的事情是 刷新总是重定向工作去 / url 不停留在匹配的路线

in app.js 检查用户是否找到 returns Content 如果不是用户 returns NotAuthenticatedContent routes

const { user } = useAuth()
if (user && user.id) {
  return <Content />
 } else
  return <NotAuthenticatedContent />
};

user 从 AuthContext

导入
function AuthProvider(props) {
 const [user, setUser] = useState()
 const { user: currentUser } = useSelector((state) => state.account)
 useEffect(() => {
  (async function () {
   if (currentUser && currentUser.jwt)
     setUser(currentUser.user)
   })();
 }, []);
 return (<AuthContext.Provider value={{user}} {...props}/>)
}
const AuthContext = createContext({})
const useAuth = () => useContext(AuthContext)
export {AuthProvider,useAuth}

我注意到 history.push('/requests') 可以转到 /requests 页面 但是当我输入 url 部分重定向到 /

使用基于网络的技术,您需要习惯使用浏览器开发人员工具。在那里你会看到很多关于空白页面的错误。

这些错误主要是由于 react、react-router、react-router-dom 的主要版本更改,部分原因是您尝试使用 npm 安装它们的方式。

要解决您的问题,首先,请确保您拥有这些工具的第 5 个版本。尝试在没有版本的情况下安装将导致安装最新版本。当您对应用的功能有信心但准备好进行大量更改时,请切换到 v6。

npx create-react-app@5 appName
npm install react-router@5
npm install react-router-dom@5

如果版本不匹配,您将在控制台上收到不兼容导入的错误,但许多错误仅在浏览器上运行时出现,因此请打开开发人员工具查看还有什么问题。

我试过你的代码片段。除了这些版本不兼容和一些逻辑错误外,他们没有问题。

  • 除非你真的改变结构,否则你不需要从映射中导出新对象,所以export default routes就足够了。

  • 您没有到登录页面的直接路径。在 content.js 的开关组件中和您的私有路由映射之外,添加 <Route exact key="/login" path="/login" render={Login}/>

  • 除此之外,请确保您的路线不会隐藏部分匹配项

我已经在 github 上上传了我的示例应用程序:react-v5-simple-login-route-layout。为此,我使用了上面的命令,删除了源文件夹中除 index.*App.js 之外的所有内容,按原样复制了 OP 的代码片段,仅编辑了我上面提到的部分,添加了缺少的页面组件和 login/logout 页面以清除本地存储和即兴布局。

我把 console.log() 放在每个地方然后弄明白了 这是 app.js

const { user } = useAuth()
if (user && user.id) {
 console.log('user logged in')
 return <Content />
} else
 console.log('user not logged in')
 return <NotAuthenticatedContent/>
}

在浏览器中 user 的第一个值或初始值为 null,在控制台中 用户未登录 已打印及以后user logged in 也被打印出来所以 user 检查是错误的然后返回 <NotAuthenticatedContent/> 有一些相同的路由比如/articles/:id,/expert