最近在写react项目的时候遇到这么一个场景,主页面访问频繁,但是有些页面返回的时候需要保持跳出时候的状态,有些页面要重新load组件。一开始遇到这个问题的时候,觉得是不是只能把需要保持当前状态的跳转页面写成一个组件,而不去跳转路由,但是这样的页面是在是有点多,这样会使主页面变得很庞大,所以只能想办法如何跳出路由时候不卸载。当时觉得很困难,直到看到了children这个属性之后才发现这个事情真的很简单。。。
children,react-router-dom中route组件的一个属性,很多人可能没有发现过这个属性,这个属性其实容易理解,就是不管路由匹配不匹配都会渲染在页面中,来看一下这个例子;
render() {
return (
<Router>
<Route path={'/my'} exact children={()=>{
return <div>my page</div>}
}>
</Route>
<Route path={'/home'} exact component={HomePage}/>
<Route path={'/person'} exact component={PersonPage}/>
</Router>
);
}
}
class HomePage extends Component {
render() {
return (
<div>
Home Page
</div>
);
}
}
const PersonPage = ()=>{
return (
<div>
Person Page
</div>
);
}
复制代码
来,我们看一下效果。
这就是children的效果,明明匹配的路由是person,但是却出现了'/my'的内容。不过这就是正是这个需求想要的,熟悉react编程的同学都知道,react都是函数,可以说是把函数式编程发挥到了极致,所以这个函数里面肯定有参数,所以我们打印一下这个children里面的参数,
<Route path={'/my'} exact children={(props)=>
console.log(props);
return <div>my page</div>}
}></Route>
复制代码
看见了参数,是不是一下就明白了如何实现效果了把, 所以我们只要判断一下是否是我们需要保持状态的路由,是的话就把children的节点隐藏点,不是的话就删除掉就能实现啦。
<Route path={'/my'} exact children={(props)=>{
console.log(props);
return props.location.pathname !== '/person'
?
<div style={{display: props.location.pathname !== '/my' ? 'none': 'block'}}>my page</div>
:
''
}}></Route>
复制代码
这样就能实现我们的需要了。不过这个属性不能用在switch里面,据说这是由于react的分型机制决定的,由于能力较差,还不能解释为什么不能再switch里面使用,所以还请大佬们请教。。。