轉自: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 {}
複製代碼