在react中使用vuex的示例代码

2020-06-13 10:32:48易采站长站整理


const connect = (mapStateToProps = () => {}) => {
return (WrappedComponent) => {
const Wrapper = class extends Component {
render() {
const store = this.context.store;
const props = Object.assign({}, this.props, mapStateToProps(store.state, this.props), {dispatch: store.dispatch, commit: store.commit});
return <WrappedComponent {...props} />
}
}
Wrapper.contextTypes = {
store: PropTypes.object
};
reaturn Wrapper;
}
}

这样一来,只要组件执行render方法,便会触发get钩子,从而使得store自动收集依赖,我们再想下依赖是什么,其实依赖应该是组件实例,那么当set钩子触发时,每个依赖(即组件实例)只要执行forceUpdate方法就可以达到rerender的效果。

但是问题是,get钩子触发时,如何确定依赖到底是谁呢?借鉴vue,我们定义一个stack,当componentWillMount时进栈,当componentDidMount时出栈


componentWillMount() {
pushTarget(this);
}

componentDidMount() {
popTarget(this);
}

这样当get钩子触发时,当前target就是目标依赖。同时应当注意,当组件update时应当重新收集依赖,因为update之后依赖关系很可能已经变化了


update() {
// 清空依赖
this.clear();
pushTarget(this);
this.forceUpdate(() => {
popTarget(this);
})
}

至此,我们的小目标已经完成了,在react中使用vuex不再是梦!

原文地址