美文网首页
redux, react-redux中的重要API解析

redux, react-redux中的重要API解析

作者: 一瓣山河 | 来源:发表于2019-05-18 12:46 被阅读0次

    Redux

    Redux的设计理念很简单: Web 应用是一个状态机,视图与状态是一一对应的,应用的状态保存在一个对象中。

    理解redux 之前,我们要知道几个概念, store, reducer, action.

    • store 掌管整个应用的状态, 整个应用只能有一个store。通过store.getState() 获取应用某个时间点的快照(状态),通过store.dispatch 分发action
      Redux 规定: 一个 State 对应一个 View。只要 State 相同,View 就相同。你知道 State,就知道 View 是什么样,反之亦然。
    • reducer
      当store收到action ,就要生成一个新的state, 这个计算过程就是reducer。reducer是一个纯函数,即相同的输入,一定得到相同的输出。
    • action
      用户不能直接修改state, state的变化必须是View 导致的, action 就是View 发出的一个通知,表示State要发生变化啦。action 是一个对象,type属性是必须的,表示action 的名称。

    redux 重要API

    redux提供了几个重要的函数:

    • createStore函数
      用来生成store, 使用方法: const store = createStore(reducer, initialState, enhancer)

    • bindActionCreators
      将 action 包装成直接可被调用的函数,用户感知不到dispatch的存在

    • combineReducers
      一个复杂的应用往往state 比较庞大,导致 Reducer 函数也比较庞大,因此如果能把reducer拆分成一个个独立的子Reducer, 最后再把他们合成一个大的reducer,处理起来就比较方便。而combineReducers就是做这件事的,该函数根据state的key去执行响应的子Reducer,并将结果合并到最终的state对象里。

    • applyMiddleware
      applyMiddleware(...middlewares) 引入中间件,比如我们经常使用的用于处理异步action的redux-thunk 中间件。实际上,中间件是一个函数,对store.dispatch函数进行了改造,在发出action和执行reducer之间,增加了一些其他的功能。

    • compose函数
      compose是一个返回依次执行参数里面的方法的函数, 其内部是通过Array.prototype.reduceRight 函数实现的,一般redux项目使用多个中间件时会用到。

    react-redux

    react-redux 提供了两个重要的函数,Provider 和 connect。

    • Provider组件
      Provider其实是一个React 组件,其原理是通过React组件的context 属性实现store 的传递, 进而拿到整个应用的state。
    // Provider 实现原理
    class Provider extends Component {
      getChildContext() {
        store: this.props.store
      }
      render() {
        const { children } = this.props
        return Children.only(children)
      }
    }
    
    Provider.childContextTypes = {
      store: React.PropTypes.object
    }
    

    上面store放在context里,这样页面组件就可以通过context 拿到store

    class PageComp extends Component {
      
      render() {
        const { store } = this.context;
        const state = store.getState();
     
        return (<div>{state.number || ''}</div>)
      }
    }
    
    PageComp.contextTypes = {
      store: React.PropTypes.object
    }
    
    • connect 函数
      connect函数是把 redux 的 dispatch 和 state 映射为 react 组件的 props中,将页面里的组件与应用的状态state真正连接起来。

    相关文章

      网友评论

          本文标题:redux, react-redux中的重要API解析

          本文链接:https://www.haomeiwen.com/subject/xvtsaqtx.html