原文链接:https://github.com/ecmadao/Co…
转载请说明出处本文不触及redux的运用要领,因而能够更适合运用过redux的玩家翻阅?
预热
柯里化函数(curry
)
浅显的来说,能够用一句话归纳综合柯里化函数:返回函数的函数
// example
const funcA = (a) => {
return const funcB = (b) => {
return a + b
}
};
上述的funcA
函数吸收一个参数,并返回一样吸收一个参数的funcB
函数。
柯里化函数有什么优点呢?
避免了给一个函数传入大批的参数–我们能够经由过程柯里化来构建相似上例的函数嵌套,将参数的代入分脱离,更有利于调试
下降耦合度和代码冗余,便于复用
举个栗子:
// 已知listA, listB两个Array,都由int构成,须要挑选出两个Array的交集
const listA = [1, 2, 3, 4, 5];
const listB = [2, 3, 4];
const checkIfDataExist = (list) => {
return (target) => {
return list.some(value => value === target)
};
};
// 挪用一次checkIfDataExist函数,并将listA作为参数传入,来构建一个新的函数。
// 而新函数的作用则是:搜检传入的参数是不是存在于listA里
const ifDataExist = checkIfDataExist(listA);
// 运用新函数来对listB里的每一个元素举行挑选
const intersectionList = listB.filter(value => ifDataExist(value));
console.log(intersectionList); // [2, 3, 4]
代码组合(compose
)
代码组合就像是数学中的连系律:
const compose = (f, g) => {
return (x) => {
return f(g(x));
};
};
// 还能够再简约点
const compose = (f, g) => (x) => f(g(x));
经由过程如许函数之间的组合,能够大大增添可读性,结果远大于嵌套一大堆的函数挪用,而且我们能够随便变动函数的挪用递次
Redux
combineReducers
// 回忆一下combineReducers的运用花样
// 两个reducer
const todos = (state = INIT.todos, action) => {
// ....
};
const filterStatus = (state = INIT.filterStatus, action) => {
// ...
};
const appReducer = combineReducers({
todos,
filterStatus
});
还记得
combineReducers
的黑魔法吗?即:
传入的Object参数中,对象的
key
与value
所代表的reducer function
同名各个
reducer function
的称号和须要传入该reducer的state
参数同名
源码标注解读(省略部份):
export default function combineReducers(reducers) {
// 第一次挑选,参数reducers为Object
// 挑选掉reducers中不是function的键值对
var reducerKeys = Object.keys(reducers);
var finalReducers = {}
for (var i = 0; i < reducerKeys.length; i++) {
var key = reducerKeys[i];
if (typeof reducers[key] === 'function') {
finalReducers[key] = reducers[key]
}
}
var finalReducerKeys = Object.keys(finalReducers)
// 二次挑选,推断reducer中传入的值是不是正当(!== undefined)
// 猎取挑选完以后的一切key
var sanityError
try {
// assertReducerSanity函数用于遍历finalReducers中的reducer,搜检传入reducer的state是不是正当
assertReducerSanity(finalReducers)
} catch (e) {
sanityError = e
}
// 返回一个function。该要领吸收state和action作为参数
return function combination(state = {}, action) {
// 假如之前的推断reducers中有非法值,则抛出毛病
if (sanityError) {
throw sanityError
}
// 假如不是production环境则抛出warning
if (process.env.NODE_ENV !== 'production') {
var warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action)
if (warningMessage) {
warning(warningMessage)
}
}
var hasChanged = false
var nextState = {}
// 遍历一切的key和reducer,分别将reducer对应的key所代表的state,代入到reducer中举行函数挪用
for (var i = 0; i < finalReducerKeys.length; i++) {
var key = finalReducerKeys[i]
var reducer = finalReducers[key]
// 这也就是为何说combineReducers黑魔法--请求传入的Object参数中,reducer function的称号和要和state同名的缘由
var previousStateForKey = state[key]
var nextStateForKey = reducer(previousStateForKey, action)
// 假如reducer返回undefined则抛出毛病
if (typeof nextStateForKey === 'undefined') {
var errorMessage = getUndefinedStateErrorMessage(key, action)
throw new Error(errorMessage)
}
// 将reducer返回的值填入nextState
nextState[key] = nextStateForKey
// 假如任一state有更新则hasChanged为true
hasChanged = hasChanged || nextStateForKey !== previousStateForKey
}
return hasChanged ? nextState : state
}
}
// 搜检传入reducer的state是不是正当
function assertReducerSanity(reducers) {
Object.keys(reducers).forEach(key => {
var reducer = reducers[key]
// 遍历悉数reducer,并给它传入(undefined, action)
// 当第一个参数传入undefined时,则为各个reducer定义的默许参数
var initialState = reducer(undefined, { type: ActionTypes.INIT })
// ActionTypes.INIT几乎不会被定义,所以会经由过程switch的default返回reducer的默许参数。假如没有指定默许参数,则返回undefined,抛出毛病
if (typeof initialState === 'undefined') {
throw new Error(
`Reducer "${key}" returned undefined during initialization. ` +
`If the state passed to the reducer is undefined, you must ` +
`explicitly return the initial state. The initial state may ` +
`not be undefined.`
)
}
var type = '@@redux/PROBE_UNKNOWN_ACTION_' + Math.random().toString(36).substring(7).split('').join('.')
if (typeof reducer(undefined, { type }) === 'undefined') {
throw new Error(
`Reducer "${key}" returned undefined when probed with a random type. ` +
`Don't try to handle ${ActionTypes.INIT} or other actions in "redux/*" ` +
`namespace. They are considered private. Instead, you must return the ` +
`current state for any unknown actions, unless it is undefined, ` +
`in which case you must return the initial state, regardless of the ` +
`action type. The initial state may not be undefined.`
)
}
})
}
createStore
// 回忆下运用要领
const store = createStore(reducers, state, enhance);
源码标注解读(省略部份):
// 关于未知的action.type,reducer必需返回默许的参数state。这个ActionTypes.INIT就能够用来监测当reducer传入未知type的action时,返回的state是不是正当
export var ActionTypes = {
INIT: '@@redux/INIT'
}
export default function createStore(reducer, initialState, enhancer) {
// 搜检你的state和enhance参数有无传反
if (typeof initialState === 'function' && typeof enhancer === 'undefined') {
enhancer = initialState
initialState = undefined
}
// 假如有传入正当的enhance,则经由过程enhancer再挪用一次createStore
if (typeof enhancer !== 'undefined') {
if (typeof enhancer !== 'function') {
throw new Error('Expected the enhancer to be a function.')
}
return enhancer(createStore)(reducer, initialState)
}
if (typeof reducer !== 'function') {
throw new Error('Expected the reducer to be a function.')
}
var currentReducer = reducer
var currentState = initialState
var currentListeners = []
var nextListeners = currentListeners
var isDispatching = false // 是不是正在分发事宜
function ensureCanMutateNextListeners() {
if (nextListeners === currentListeners) {
nextListeners = currentListeners.slice()
}
}
// 我们在action middleware中常常运用的getState()要领,返回当前state
function getState() {
return currentState
}
// 注册listener,同时返回一个作废事宜注册的要领。当挪用store.dispatch的时刻挪用listener
function subscribe(listener) {
if (typeof listener !== 'function') {
throw new Error('Expected listener to be a function.')
}
var isSubscribed = true
ensureCanMutateNextListeners()
nextListeners.push(listener)
return function unsubscribe() {
if (!isSubscribed) {
return
}
isSubscribed = false
// 从nextListeners中去撤除当前listener
ensureCanMutateNextListeners()
var index = nextListeners.indexOf(listener)
nextListeners.splice(index, 1)
}
}
// dispatch要领吸收的action是个对象,而不是要领。
// 这个对象实际上就是我们自定义action的返回值,由于dispatch的时刻,已挪用过我们的自定义action了,比方 dispatch(addTodo())
function dispatch(action) {
if (!isPlainObject(action)) {
throw new Error(
'Actions must be plain objects. ' +
'Use custom middleware for async actions.'
)
}
if (typeof action.type === 'undefined') {
throw new Error(
'Actions may not have an undefined "type" property. ' +
'Have you misspelled a constant?'
)
}
// 挪用dispatch的时刻只能一个个挪用,经由过程dispatch推断挪用的状况
if (isDispatching) {
throw new Error('Reducers may not dispatch actions.')
}
try {
isDispatching = true
currentState = currentReducer(currentState, action)
} finally {
isDispatching = false
}
// 遍历挪用各个linster
var listeners = currentListeners = nextListeners
for (var i = 0; i < listeners.length; i++) {
listeners[i]()
}
return action
}
// Replaces the reducer currently used by the store to calculate the state.
function replaceReducer(nextReducer) {
if (typeof nextReducer !== 'function') {
throw new Error('Expected the nextReducer to be a function.')
}
currentReducer = nextReducer
dispatch({ type: ActionTypes.INIT })
}
// 当create store的时刻,reducer会接收一个type为ActionTypes.INIT的action,使reducer返回他们默许的state,如许能够疾速的构成默许的state的构造
dispatch({ type: ActionTypes.INIT })
return {
dispatch,
subscribe,
getState,
replaceReducer
}
}
thunkMiddleware
源码及其简朴几乎给跪…
// 返回以 dispatch 和 getState 作为参数的action
export default function thunkMiddleware({ dispatch, getState }) {
return next => action => {
if (typeof action === 'function') {
return action(dispatch, getState);
}
return next(action);
};
}
applyMiddleware
先温习下用法:
// usage
import {createStore, applyMiddleware} from 'redux';
import thunkMiddleware from 'redux-thunk';
const store = createStore(
reducers,
state,
applyMiddleware(thunkMiddleware)
);
applyMiddleware
起首吸收thunkMiddleware
作为参数,二者组合成为一个新的函数(enhance
),以后在createStore
内部,由于enhance
的存在,将会变成返回enhancer(createStore)(reducer, initialState)
源码标注解读(省略部份):
// 定义一个代码组合的要领
// 传入一些function作为参数,返回其链式挪用的形状。比方,
// compose(f, g, h) 终究返回 (...args) => f(g(h(...args)))
export default function compose(...funcs) {
if (funcs.length === 0) {
return arg => arg
} else {
const last = funcs[funcs.length - 1]
const rest = funcs.slice(0, -1)
return (...args) => rest.reduceRight((composed, f) => f(composed), last(...args))
}
}
export default function applyMiddleware(...middlewares) {
// 终究返回一个以createStore为参数的匿名函数
// 这个函数返回另一个以reducer, initialState, enhancer为参数的匿名函数
return (createStore) => (reducer, initialState, enhancer) => {
var store = createStore(reducer, initialState, enhancer)
var dispatch
var chain = []
var middlewareAPI = {
getState: store.getState,
dispatch: (action) => dispatch(action)
}
// 每一个 middleware 都以 middlewareAPI 作为参数举行注入,返回一个新的链。此时的返回值相当于挪用 thunkMiddleware 返回的函数: (next) => (action) => {} ,吸收一个next作为其参数
chain = middlewares.map(middleware => middleware(middlewareAPI))
// 并将链代入进 compose 构成一个函数的挪用链
// compose(...chain) 返回形如(...args) => f(g(h(...args))),f/g/h都是chain中的函数对象。
// 在现在只要 thunkMiddleware 作为 middlewares 参数的状况下,将返回 (next) => (action) => {}
// 以后以 store.dispatch 作为参数举行注入
dispatch = compose(...chain)(store.dispatch)
return {
...store,
dispatch
}
}
}
一脸懵逼?没紧要,来连系实际运用总结一下:
当我们搭配redux-thunk
这个库的时刻,在redux
合营components
时,平常这么写
import thunkMiddleware from 'redux-thunk';
import { createStore, applyMiddleware, combineReducer } from 'redux';
import * as reducers from './reducers.js';
const appReducer = combineReducer(reducers);
const store = createStore(appReducer, initialState, applyMiddleware(thunkMiddleware));
还记得当createStore
收到的参数中有enhance
时会怎么做吗?
// createStore.js
if (typeof enhancer !== 'undefined') {
if (typeof enhancer !== 'function') {
throw new Error('Expected the enhancer to be a function.')
}
return enhancer(createStore)(reducer, initialState)
}
也就是说,会变成下面的状况
applyMiddleware(thunkMiddleware)(createStore)(reducer, initialState)
applyMiddleware(thunkMiddleware)
applyMiddleware
吸收thunkMiddleware
作为参数,返回形如(createStore) => (reducer, initialState, enhancer) => {}
的函数。
applyMiddleware(thunkMiddleware)(createStore)
以 createStore 作为参数,挪用上一步返回的函数(reducer, initialState, enhancer) => {}
applyMiddleware(thunkMiddleware)(createStore)(reducer, initialState)
以(reducer, initialState)为参数举行挪用。
在这个函数内部,thunkMiddleware
被挪用,其作用是监测type
是function
的action
因而,假如dispatch
的action
返回的是一个function
,则证实是中间件,则将(dispatch, getState)
作为参数代入个中,举行action
内部下一步的操纵。不然的话,以为只是一个平常的action
,将经由过程next
(也就是dispatch
)进一步分发。
也就是说,applyMiddleware(thunkMiddleware)
作为enhance
,终究起了如许的作用:
对dispatch
挪用的action
(比方,dispatch(addNewTodo(todo)))
举行搜检,假如action
在第一次挪用以后返回的是function
,则将(dispatch, getState)
作为参数注入到action
返回的要领中,不然就平常对action
举行分发,如许一来我们的中间件就完成喽~
因而,当action
内部须要猎取state
,或许须要举行异步操纵,在操纵完成以后举行事宜挪用分发的话,我们就能够让action
返回一个以(dispatch, getState)
为参数的function
而不是平常的Object
,enhance
就会对其举行检测以便准确的处置惩罚。
bindActionCreator
这个要领觉得比较少见,我个人也很少用到
在传统写法下,当我们要把 state 和 action 注入到子组件中时,平常会这么做:
import { connect } from 'react-redux';
import {addTodo, deleteTodo} from './action.js';
class TodoComponect extends Component {
render() {
return (
<ChildComponent
deleteTodo={this.props.deleteTodo}
addTodo={this.props.addTodo}
/>
)
}
}
function mapStateToProps(state) {
return {
state
}
}
function mapDispatchToProps(dispatch) {
return {
deleteTodo: (id) => {
dispatch(deleteTodo(id));
},
addTodo: (todo) => {
dispatch(addTodo(todo));
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(TodoComponect);
运用bindActionCreators
能够把 action 转为同名 key 的对象,但运用 dispatch 把每一个 action 包围起来挪用
唯一运用 bindActionCreators 的场景是当你须要把 action creator 往下传到一个组件上,却不想让这个组件觉察到 Redux 的存在,而且不愿望把 Redux store 或 dispatch 传给它。
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import {addTodo, deleteTodo} as TodoActions from './action.js';
class TodoComponect extends React.Component {
// 在本组件内的运用
addTodo(todo) {
let action = TodoActions.addTodo(todo);
this.props.dispatch(action);
}
deleteTodo(id) {
let action = TodoActions.deleteTodo(id);
this.props.dispatch(action);
}
render() {
let dispatch = this.props.dispatch;
// 传递给子组件
let boundActionCreators = bindActionCreators(TodoActions, dispatch);
return (
<ChildComponent
{...boundActionCreators}
/>
)
}
}
function mapStateToProps(state) {
return {
state
}
}
export default connect(mapStateToProps)(TodoComponect)
bindActionCreator
源码剖析
function bindActionCreator(actionCreator, dispatch) {
return (...args) => dispatch(actionCreator(...args))
}
// bindActionCreators期待一个Object作为actionCreators传入,内里是 key: action
export default function bindActionCreators(actionCreators, dispatch) {
// 假如只是传入一个action,则经由过程bindActionCreator返回被绑定到dispatch的函数
if (typeof actionCreators === 'function') {
return bindActionCreator(actionCreators, dispatch)
}
if (typeof actionCreators !== 'object' || actionCreators === null) {
throw new Error(
`bindActionCreators expected an object or a function, instead received ${actionCreators === null ? 'null' : typeof actionCreators}. ` +
`Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?`
)
}
// 遍历并经由过程bindActionCreator分发绑定至dispatch
var keys = Object.keys(actionCreators)
var boundActionCreators = {}
for (var i = 0; i < keys.length; i++) {
var key = keys[i]
var actionCreator = actionCreators[key]
if (typeof actionCreator === 'function') {
boundActionCreators[key] = bindActionCreator(actionCreator, dispatch)
}
}
return boundActionCreators
}
react-redux
Provider
export default class Provider extends Component {
getChildContext() {
// 将其声明为 context 的属性之一
return { store: this.store }
}
constructor(props, context) {
super(props, context)
// 吸收 redux 的 store 作为 props
this.store = props.store
}
render() {
return Children.only(this.props.children)
}
}
if (process.env.NODE_ENV !== 'production') {
Provider.prototype.componentWillReceiveProps = function (nextProps) {
const { store } = this
const { store: nextStore } = nextProps
if (store !== nextStore) {
warnAboutReceivingStore()
}
}
}
Provider.propTypes = {
store: storeShape.isRequired,
children: PropTypes.element.isRequired
}
Provider.childContextTypes = {
store: storeShape.isRequired
}
connect
传入mapStateToProps
,mapDispatchToProps
,mergeProps
,options
。
起首猎取传入的参数,假如没有则以默许值替代
const defaultMapStateToProps = state => ({}) // eslint-disable-line no-unused-vars
const defaultMapDispatchToProps = dispatch => ({ dispatch })
const { pure = true, withRef = false } = options
以后,经由过程
const finalMergeProps = mergeProps || defaultMergeProps
挑选兼并stateProps
,dispatchProps
,parentProps
的体式格局,默许的兼并体式格局 defaultMergeProps
为:
const defaultMergeProps = (stateProps, dispatchProps, parentProps) => ({
...parentProps,
...stateProps,
...dispatchProps
})
返回一个以 Component 作为参数的函数。在这个函数内部,生成了一个叫做Connect
的 Component
// ...
return function wrapWithConnect(WrappedComponent) {
const connectDisplayName = `Connect(${getDisplayName(WrappedComponent)})`
// 搜检参数正当性
function checkStateShape(props, methodName) {}
// 兼并props
function computeMergedProps(stateProps, dispatchProps, parentProps) {
const mergedProps = finalMergeProps(stateProps, dispatchProps, parentProps)
if (process.env.NODE_ENV !== 'production') {
checkStateShape(mergedProps, 'mergeProps')
}
return mergedProps
}
// start of Connect
class Connect extends Component {
constructor(props, context) {
super(props, context);
this.store = props.store || context.store
const storeState = this.store.getState()
this.state = { storeState }
this.clearCache()
}
computeStateProps(store, props) {
// 挪用configureFinalMapState,运用传入的mapStateToProps要领(或默许要领),将state map进props
}
configureFinalMapState(store, props) {}
computeDispatchProps(store, props) {
// 挪用configureFinalMapDispatch,运用传入的mapDispatchToProps要领(或默许要领),将action运用dispatch封装map进props
}
configureFinalMapDispatch(store, props) {}
// 推断是不是更新props
updateStatePropsIfNeeded() {}
updateDispatchPropsIfNeeded() {}
updateMergedPropsIfNeeded() {}
componentDidMount() {
// 内部挪用this.store.subscribe(this.handleChange.bind(this))
this.trySubscribe()
}
handleChange() {
const storeState = this.store.getState()
const prevStoreState = this.state.storeState
// 对数据举行监听,发送转变时挪用
this.setState({ storeState })
}
// 作废监听,消灭缓存
componentWillUnmount() {
this.tryUnsubscribe()
this.clearCache()
}
render() {
this.renderedElement = createElement(WrappedComponent,
this.mergedProps
)
return this.renderedElement
}
}
// end of Connect
Connect.displayName = connectDisplayName
Connect.WrappedComponent = WrappedComponent
Connect.contextTypes = {
store: storeShape
}
Connect.propTypes = {
store: storeShape
}
return hoistStatics(Connect, WrappedComponent)
}
// ...
我们瞥见,在connect的末了,返回了运用hoistStatics
包装的Connect
和WrappedComponent
hoistStatics是什么鬼?为何运用它?
Copies non-react specific statics from a child component to a parent component. Similar to Object.assign, but with React static keywords blacklisted from being overridden.
也就是说,它相似于Object.assign
,作用是将子组件中的 static 要领复制进父组件,但不会掩盖组件中的关键字要领(如 componentDidMount)
import hoistNonReactStatic from 'hoist-non-react-statics';
hoistNonReactStatic(targetComponent, sourceComponent);