转自:jeezlee/www.pickerlee.comjavascript
假如咱们有以下路由:java
<Route path="articles/:articleId" component={Article} />
复制代码
这时咱们从articles/1
跳转至articles/2
时componentDidMount
钩子函数不会按照预期执行, 缘由是对react来讲这2个页面是相同的组件,或者说articles/1
组件不会销毁,一样也不会执行componentDidMount
react
在componentWillReceiveProps
钩子函数中手动触发componentWillUnmount
和componentDidMount
函数。git
/** * 该装饰器函数接受一个或多个连续的字符串 * eg:routeStateChnageToReload('state') or routeStateChnageToReload('state1', 'state2') */
const routeStateChnageToReload = (...states) => {
return target => {
const oldWillUnmount = target.prototype.componentWillUnmount;
const oldDidMount = target.prototype.componentDidMount;
const oldWillReceiveProps = target.prototype.componentWillReceiveProps;
target.prototype.componentWillReceiveProps = function(nextProps) {
const changed = Boolean(states.find(state => {
return this.props.routeParams[state] !== nextProps.routeParams[state];
}));
if (changed) {
oldWillUnmount && oldWillUnmount.call(this);
oldDidMount && oldDidMount.call(this);
}
oldWillReceiveProps && oldWillReceiveProps.call(this, nextProps);
};
};
};
复制代码
@routeStateChnageToReload('articleId')
export default class Article extends React.Component {}
复制代码