react-redux中的重要API解析

dedux

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

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

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

const mapDispatchToProps = dispatch => bindActionCreators(actions, dispatch);
return connect(mapStateToProps, mapDispatchToProps)(Node);
  1. combineReducers

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

import { combineReducers } from 'redux';
import { storeReducer } from './store/reducer';
import { reserveReducer } from './reserve/reducer';

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

  2. compose函数

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

react-redux

Provider组件
Provider其实是一个React 组件,其原理是通过React组件的context 属性实现store 的传递, 进而拿到整个应用的state。

connect 函数
connect函数是把 redux 的 dispatch 和 state 映射为 react 组件的 props中,将页面里的组件与应用的状态state真正连接起来。

猜你喜欢

转载自www.cnblogs.com/smzd/p/12625249.html