react、redux、react-redux之间的关系
React一些小型项目,只使用 其实 Redux其实我们只是想找个地方存放一些共享数据而已,大家都可以获取到,也都可以进行修改,仅此而已。 现在要写这样一个函数,其满足:
function createStore(reducer,initialState) { // currentState就是那个数据 let currentState = initialState; let listener = () => {}; function getState() { return currentState; } function dispatch(action) { currentState = reducer(currentState,action); // 更新数据 listener(); // 执行订阅函数 return action; } function subscribe(newListener) { listener = newListener; // 取消订阅函数 return function unsubscribe() { listener = () => {}; }; } return { getState,dispatch,subscribe }; } const store = createStore(reducer); store.getState(); // 获取数据 store.dispatch({type: 'ADD_TODO'}); // 更新数据 store.subscribe(() => {/* update UI */}); // 注册订阅函数 更新数据执行的步骤:
这样就实现了一个store,提供一个数据存储中心,可以供外部访问、修改等,这就是Redux的主要思想。 现在既然有了一个安全的地方存取数据,怎么结合到React里面呢? React-Redux由于全局变量有诸多的缺点,那就换个思路,把store直接集成到React应用的顶层props里面,只要各个子组件能访问到顶层props就行了,比如这样: <TopWrapComponent store={store}> <App /> </TopWrapComponent>, React恰好提供了这么一个钩子,Context,用法很简单,看一下官方demo就明了。现在各个子组件已经能够轻易地访问到store了,接下来就是子组件把store中用到的数据取出来、修改、以及订阅更新UI等。每个子组件都需要这样做一遍,显然,肯定有更便利的方法:高阶组件。通过高阶组件把 下面是这个高阶组件的大致实现: function connect(mapStateToProps,mapDispatchToProps) { return function(WrappedComponent) { class Connect extends React.Component { componentDidMount() { // 组件加载完成后订阅store变化,如果store有变化则更新UI this.unsubscribe = this.context.store.subscribe(this.handleStoreChange.bind(this)); } componentWillUnmount() { // 组件销毁后,取消订阅事件 this.unsubscribe(); } handleStoreChange() { // 更新UI this.forceUpdate(); } render() { return ( <WrappedComponent {...this.props} {...mapStateToProps(this.context.store.getState())} // 参数是store里面的数据 {...mapDispatchToProps(this.context.store.dispatch)} // 参数是store.dispatch /> ); } } Connect.contextTypes = { store: PropTypes.object }; return Connect; }; } 使用connect的时候,我们知道要写一些样板化的代码,比如 const mapStateToProps = state => { return { count: state.count }; }; const mapDispatchToProps = dispatch => { return { dispatch }; }; export default connect(mapStateToProps,mapDispatchToProps)(Child); // 上述代码执行之后,可以看到connect函数里面的 <WrappedComponent {...this.props} {...mapStateToProps(this.context.store.getState())} {...mapDispatchToProps(this.context.store.dispatch)} /> // 就变成了 <WrappedComponent {...this.props} {count: store.getState().count} {dispatch: store.dispatch} /> // 这样,子组件Child的props里面就多了count和dispatch两个属性 // count可以用来渲染UI,dispatch可以用来触发回调 So,这样就OK了?OK了。通过一个闭包生成一个数据中心store,然后把这个store绑定到React的顶层props里面,子组件通过HOC建立与顶层props.store的联系,进而获取数据、修改数据、更新UI。这里主要讲了一下三者怎么窜在一起的,如果想了解更高级的功能,比如redux中间件、reducer拆分、connect的其他参数等,可以去看一下对应的源码。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |