import {lazy} from "react"
const Login = lazy(()=>import("../pages/Login"))
const Home = lazy(()=>import('../pages/Home'))
const History = lazy(()=>import("../pages/History"))
const My = lazy(()=>import("../pages/My"))
const Line = lazy(()=>import("../pages/Line"))
const Weight = lazy(()=>import("../pages/Weight"))
const Callcenter = lazy(()=>import("../pages/Calcenter"))
const Shop = lazy(()=>import("../pages/Shop"))
const Homeson = lazy(()=>import("../pages/Homeson"))
const routerConfig = [
{
path:"/login",
element:<Login></Login>
},
{
path:"/my",
element:<My></My>,
},
{
path:"/line",
element:<Line></Line>,
tit:"近七天体重"
},
{
path:"/history",
element:<History></History>,
tit:"历史"
},
{
path:"/weight",
element:<Weight></Weight>,
tit:"体重"
},
{
path:"/home",
element:<Home></Home>,
children:[
{
path:"/home/homeson",
element:<Homeson></Homeson>
},
{
path:"/home/callcenter",
element:<Callcenter></Callcenter>
},
{
path:"/home/shop",
element:<Shop></Shop>
}
]
}
]
export default routerConfig
组件
import React,{useMemo , useState} from 'react'
import {NavBar,Toast} from "react-vant"
import routerConfig from "../router"
import {useParams,useLocation,useMatch} from "react-router-dom"
function Myheader() {
// let [title, setTitle] = useState("历史记录")
// let [flag, setFlag] = useState(true)
// let params = useParams()
let location = useLocation()
// let Match = useMatch(location.pathname)
const title = useMemo(() => {
const formatTitle = (arr, res = []) => arr.reduce((def, val) => {
if(val.children) {
formatTitle(val.children, def)
} else {
// 如果当前的数组便利的这一项得路径等于当前路由的路径,往累计值里push
console.log("我进来了");
if ( val.path === location.pathname) {
console.log("我进小门了");
def.push(val);
}
// val.path === location.pathname && def.push(val);
}
return def;
}, res)
const curParams = formatTitle(routerConfig); // 获取路由表里的整个对象
console.log(curParams,"4444");
const targetParams = curParams[curParams.length - 1];
console.log(targetParams,"3333");
return targetParams?.tit || targetParams?.path
}, [location.pathname])
console.log(title,"222");
// console.log(params);
// console.log(location);
// useEffect(()=>{
// // console.log(location.pathname);
// if (location.pathname === "/history") {
// setTitle("历史记录")
// } else if (location.pathname === "/weight") {
// setTitle("体重")
// } else if (location.pathname === "/line") {
// setTitle("近七天体重")
// }
// if (location.pathname === "/login" ) {
// setFlag(false)
// } else {
// setFlag(true)
// }
// },[location.pathname])
return (
<div>
{
location.pathname !== '/login' && (
<NavBar
title={title}
leftText="返回"
rightText="按钮"
onClickLeft={() => Toast('返回')}
onClickRight={() => Toast('按钮')}
/>
)
}
</div>
)
}
export default Myheader