monsterooo / blog

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

recompose withStateHandlers #16

Open monsterooo opened 6 years ago

monsterooo commented 6 years ago

withStateHandlers 介绍

withStateHandlers就是withStatewithHandlers的结合并且对同一个state会进行多中操作时使用,它可以把statestate initialset state handler在一个地方进行创建,每个set state handler都是两个高阶函数包装的,第一个高阶函数接收(state, props),第二个高阶函数接收调用函数的参数。set state handler函数返回一个对象这个对象用于更新state

withStateHandlers Flow Type

withStateHandlers(
  initialState: Object | (props: Object) => any,
  stateUpdaters: {
    [key: string]: (state:Object, props:Object) => (...payload: any[]) => Object
  }
)

withStateHandlers 实例

const Foo = compose(
  withStateHandlers(
    ({ initialCount = 0 }) => ({
      counter: initialCount
    }),
    {
      handleIncrement: ({ counter }) => (value) => ({
        counter: counter + value,
      }),
      handleDecrement: ({ counter }) => (value) => ({
        counter: counter - value,
      }),
      handleReset: () => (initialCount = 0) => ({
        counter: initialCount,
      }),
    }
  ),
)(({ counter, handleIncrement, handleDecrement, handleReset }) => (
  <div>
    <p>Counter:{counter}</p>
    <button onClick={() => handleIncrement(1)}>增加</button>
    <button onClick={() => handleDecrement(1)}>减少</button>
    <button onClick={() => handleReset(0)}>重置</button>
  </div>
))

在线DEMO

codepen在线预览