monsterooo / blog

and make promises by the hours
MIT License
14 stars 1 forks source link

recompose withReducer #18

Open monsterooo opened 6 years ago

monsterooo commented 6 years ago

withReducer 介绍

withReducer类似于withState(),但是它的更新模式使用了redux相通的方法。withReducer接收4个参数,第一个参数为state 名称,第二个参数为dispatch 方法名,第三个参数为state 更新函数,第四个参数为初始化状态。withReducerwithState是同样的操作,他们的数据都是保存在代理组件的state中。再向外暴露一个更新的方法。

withReducer Flow Type

withReducer<S, A>(
  stateName: string,
  dispatchName: string,
  reducer: (state: S, action: A) => S,
  initialState: S | (ownerProps: Object) => S
): HigherOrderComponent

withReducer 实例

const { compose, withReducer } = Recompose;

const Foo = compose(
  withReducer('state', 'dispatch', (state, action) => {
    if(action.type === 'SETCOUNTER') {
      return { ...state, counter: action.value };
    }
    return state;
  }, { counter: 0 }),
)(({ state: { counter }, dispatch }) => (
  <div>
    <p>Counter: {counter}</p>
    <button onClick={() => dispatch({ type: 'SETCOUNTER', value: 10 })}>设置Counter</button>
  </div>
))

在线DEMO

codepen在线预览