简体   繁体   中英

recompose withState how to update on props changes

I have a higher order component that I try to modify a bit (I'm not familiar with recompose).

So thats my component:

<Map mycenter={mycenter}  />

I want the map-component to update or to rerendered if the mycenter is updated. I'm trying to modify the code from https://github.com/istarkov/google-map-thousands-markers/blob/master/src/Map.js

I made some modifications to the code. First, the map center is set to mycenter. That works.

withState('mapParams', 'setMapParams', ({ mycenter }) => ({ center:mycenter, zoom: 12 })),

After that the user can click somewhere and the center will be modified

withHandlers({
    onMapParamsChange: ({ setMapParams }) => ({ center, zoom, bounds }) => {
      setMapParams({ center, zoom, bounds });
      console.log('setMapParams', { center, zoom });
    },

Is there a way so that the component rerenders or the center is updated if "mycenter" is updated?

Currently, the best way is to use lifecycle. the callback of initial state ( ({ mycenter }) => ({ center:mycenter, zoom: 12 }) ) happens only once.

const enhanceMap = compose(
  withState('mapParams', 'setMapParams', ({ mycenter }) => ({ center: mycenter, zoom: 12 })),
  withStateHandlers({...}),
  lifecycle({
    componentWillUpdate(nextProps) {
      if (this.props.mycenter !== nextProps.mycenter)
        this.setState({mapParams: { center: nextProps.mycenter, zoom: 12 }})
    }
  })
)

Hope this don't come too late.

I find transforming props to state a little bit messy..

Right now, recompose allows you to send a function as a parameter for withProps method. You can do something like:

withProps( props => ({
  mycenter: props.mycenter,
  zoom: 12,
}))

This way, you will propagate your props down to your component, and it will update whenever the props change.

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