最近在写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>

<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>

