undefined
来源:20-9 完成头部交互与动态面包屑
weixin_慕设计4067753
2023-08-02

登陆后退出后重登就会出现该问题。后端数据调用的线上。我下载了源代码尝试了下 也是出现该问题。|
HomeAside.tsx:21 Uncaught TypeError: Cannot read properties of undefined (reading ‘includes’)
1回答
-
西门老舅
2023-08-03
你好,在BeforeEach.tsx页面确实有一些考虑欠缺,对于异步的执行顺序出现了一些问题,下面是修改后的代码,可以对照一下修改的部分,添加了loading状态,在异步没有完成前先渲染null,等异步结束后,再渲染页面。
import React, { useState } from 'react'
import { useLocation, matchRoutes, Navigate } from 'react-router-dom'
import { routes } from '../../router'
import { useAppDispatch } from '../../store'
import { infosAction, updateInfos } from '../../store/modules/users'
import type { Infos } from '../../store/modules/users'
import { useSelector } from 'react-redux'
import type { RootState } from '../../store'
import _ from 'lodash'
interface BeforeEachProps {
children?: React.ReactNode
}
export default function BeforeEach(props: BeforeEachProps) {
const [loading, setLoading] = useState(true)
const token = useSelector((state: RootState)=> state.users.token)
const infos = useSelector((state: RootState)=> state.users.infos)
const dispatch = useAppDispatch()
const location = useLocation()
const matchs = matchRoutes(routes, location)
if( Array.isArray(matchs) ){
const meta = matchs[matchs.length-1].route.meta
const name = matchs[matchs.length-1].route.name
if(meta?.auth && _.isEmpty(infos) ){
if(token){
dispatch(infosAction()).then((action)=>{
const {errcode, infos} = (action.payload as {[index: string]: unknown}).data as {[index: string]: unknown}
if(errcode === 0){
setLoading(false)
dispatch(updateInfos(infos as Infos))
}
})
if(loading) {
return null
}
}
else{
return <Navigate to="/login" />
}
}
else if( Array.isArray(infos.permission) && !infos.permission.includes(name) ){
return <Navigate to="/403" />
}
}
if( token && location.pathname === '/login' ){
return <Navigate to="/" />
}
return (
<>{ props.children }</>
)
}
10
相似问题