1.常用轮子分析
react-live-route -- 重写可以实现我们想要的功能,但成本也比较高,需要注意对原始 <Route> 功能的保存,以及多个 react-router 版本的兼容 185
react-keeper -- 完全替换掉路由方案是一个风险较大的事情,需要较为慎重地考虑 716
react-router-cache-route -- 由于不再是组件卸载,所以和 TransitionGroup 配合得不好,导致转场动画难以实现 492
react-activation -- 其 children 属性抽取出来,渲染到一个不会被卸载的组件内 245
react-keep-alive -- 真实 KeepAlive 功能的实现 438
2.最终选择 react-activation
(1)安装 react-activation 模块
yarn add react-activation
(2)引用
import * as React from "react";
import {
RouteComponentProps,
Redirect,
Switch,
Route,
withRouter,
} from "react-router-dom";
import KeepAlive, { AliveScope } from "react-activation";
import Home from "./pages/home";
import HomeChapter from "./pages/home/chapter";
interface IProps extends RouteComponentProps {
match: any;
}
class HomePage extends React.Component<IProps, {}> {
render() {
return (
<AliveScope>
<Switch>
<Redirect
exact
from={`${this.props.match.url}`}
to={`${this.props.match.url}/home`}
/>
<Route exact path={`${this.props.match.url}/home`} component={Home} />
<Route
path={`${this.props.match.url}/home/chapter`}
// component={HomeChapter}
render={(props) => (
<KeepAlive when={true}>
<HomeChapter {...props} />
</KeepAlive>
)}
/>
</Switch>
</AliveScope>
);
}
}
export default withRouter(HomePage);
.
