解決React-中已掛載組件不能執行componentDidMount鉤子函數的問題

轉自:jeezlee/www.pickerlee.comjavascript

Issue descripttion

假如咱們有以下路由:java

<Route path="articles/:articleId" component={Article} />
複製代碼

這時咱們從articles/1跳轉至articles/2componentDidMount鉤子函數不會按照預期執行, 緣由是對react來講這2個頁面是相同的組件,或者說articles/1組件不會銷燬,一樣也不會執行componentDidMountreact

Solution

componentWillReceiveProps鉤子函數中手動觸發componentWillUnmountcomponentDidMount函數。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 {}
複製代碼
相關文章
相關標籤/搜索