简体   繁体   中英

Can't change the state withStateHandlers from recompose

I have this button and playing around withStateHandlers from recompose . The goal is just to change button state from active: false to active: true .

const EnhancedButton = withStateHandlers(
  ({ initialState = false }) => ({
    active: initialState
  }),
  {
    onTrigger: ({ active }) => ({
      active: true
    })
  }
)(({ active, onTrigger, children, id }) => {
  console.log(active)
  return (
    <Button
      onClick={() => onTrigger()}
      toggle
      active={active}
      size="massive"
      style={styles.button}
      as={Link}
      to={`/${id}`}
    >
      {children}
    </Button>
  )
})

I click on the button, then I get redirected to new page, then I go back and the button is still active: false where I expect it to be active: true

The docs for withStateHandlers specify:

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

Which means that each state-updater property is a function that gets state and props arguments and returns another function, which in turn takes the optional payload arguments (ie whatever you pass as arguments when you call onTrigger ) and returns the new state.

Your onTrigger returns the new state instead of a function, so the type is incorrect. If you wrap the result in an arrow function, it should work:

onTrigger: ({ active }) => () => ({
  active: true
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM