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);
.
