react的路由 卡了一上午,我的理想化出来了
如上我已经对路由数据进行了构建,下面我只需要一个方法生成他
function generateRoute(value){ if(value.children){ return ( <React.Fragment key={param.path} > <Route path={param.path} > <param.component> { value.children.map((item)=>{ return generateRoute(item) }) } </param.component> </Route> </React.Fragment> ) } return <Route key={value.path} path={value.path} component={value.component} /> } function app(){ return ( <Switch> { router.map(item=>{ return generateRoute(item) }) } </Switch> ) }在一系列的转化下他会生成这个东西
<Switch> <Route path='/record' component={record}></Route> <> <Route path='/'> <Home> { <Route path='/feedBack' component={feedBack} /> <Route path='/children' component={Children} /> } </Home> </Route> </> </Switch> //在这里我们看到了<Home>组件,这样在Home组件中我们可以通过this.props.children来获取传入的组件,类似于vue的插槽在Home的组件中的用法
import React, { useEffect } from "react"; import { useHistory } from "react-router-dom"; const Tool = (props) => { const history = useHistory() useEffect(()=>{ //这里相当于redirect的作用,可以根据自己的需求去更改。 if(history.location.pathname == '/'){ console.log(history.push('/todolist')); } },[]) return( <div> <h1>tool</h1> <div> { props.children } </div> <footer>haha</footer> </div> ) } export default Tool卡了我一个小时的东西只有一个/
//熟悉vue路由的小伙伴都知道,子路由的path是不会加/的 const router = [ { path:'/record', component:record }, { path:'/', component:home, redirect:'/feedBack', children:[ { path:'/feedBack',//就是这里vue的话会写成feedBack,但是react会/ component:feedBack } ] }, ] //就这样一个小时 我很开心