解决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 {}
复制代码
相关文章
相关标签/搜索