Cheat Sheet速查表
跳转到主要内容

Redux 资源导航 速查表

本文根据 Devhints / Awesome Redux 翻译。代码示例及版本范围沿用原文。原文标注更新日期:2017-11-19。

redux-actions

以 Flux 标准 Action 格式创建 Action 创建函数(Action Creators)。

increment = createAction('INCREMENT', amount => amount)
increment = createAction('INCREMENT')  // same
increment(42) === { type: 'INCREMENT', payload: 42 }
// Errors are handled for you:
err = new Error()
increment(err) === { type: 'INCREMENT', payload: err, error: true }

redux-actions

flux-standard-action

Flux Action 对象的标准。一个 Action 可以包含 error, payload 以及 meta ,除此之外别无他物。

{ type: 'ADD_TODO', payload: { text: 'Work it' } }
{ type: 'ADD_TODO', payload: new Error(), error: true }

flux-standard-action

redux-multi

在单个 Action 创建函数中分发(Dispatch)多个 Action。

store.dispatch([
  { type: 'INCREMENT', payload: 2 },
  { type: 'INCREMENT', payload: 3 }
])

redux-multi

reduce-reducers

合并 Reducer(类似于 combineReducers()),但不包含命名空间相关的“魔法”逻辑。

re = reduceReducers(
  (state, action) => state + action.number,
  (state, action) => state + action.number
)

re(10, { number: 2 })  //=> 14

reduce-reducers

redux-logger

将 Action 记录到控制台。

// Nothing to see here

redux-logger

异步

redux-promise

将 Pass(Promise)转换为 Action。分发一个 Flux 标准 Action。

increment = createAction('INCREMENT')  // redux-actions
increment(Promise.resolve(42))

redux-promise

redux-promises

也差不多是这样。其工作方式是允许你传入 thunk(函数) (函数)作为 dispatch()。此外还具备“空闲检查”(idle checking)功能。

fetchData = (url) => (dispatch) => {
  dispatch({ type: 'FETCH_REQUEST' })
  fetch(url)
    .then((data) => dispatch({ type: 'FETCH_DONE', data })
    .catch((error) => dispatch({ type: 'FETCH_ERROR', error })
})

store.dispatch(fetchData('/posts'))
// That's actually shorthand for:
fetchData('/posts')(store.dispatch)

redux-promises

redux-effects

以声明式方式处理 Pass 副作用,从而保持 action 的纯粹性。

{
  type: 'EFFECT_COMPOSE',
  payload: {
    type: 'FETCH'
    payload: {url: '/some/thing', method: 'GET'}
  },
  meta: {
    steps: [ [success, failure] ]
  }
}

redux-effects

redux-thunk

允许将 Pass “thunk” 作为 action 使用。与 redux-promises 非常相似,但支持 getState。

fetchData = (url) => (dispatch, getState) => {
  dispatch({ type: 'FETCH_REQUEST' })
  fetch(url)
    .then((data) => dispatch({ type: 'FETCH_DONE', data })
    .catch((error) => dispatch({ type: 'FETCH_ERROR', error })
})

store.dispatch(fetchData('/posts'))
// That's actually shorthand for:
fetchData('/posts')(store.dispatch, store.getState)
// Optional: since fetchData returns a promise, it can be chained
// for server-side rendering
store.dispatch(fetchPosts()).then(() => {
  ReactDOMServer.renderToString(<MyApp store={store} />)
})

redux-thunk