recompose withState how to update on props changes

2019-02-26 02:04发布

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?

2条回答
不美不萌又怎样
2楼-- · 2019-02-26 02:33

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 }})
    }
  })
)
查看更多
我只想做你的唯一
3楼-- · 2019-02-26 02:39

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.

查看更多
登录 后发表回答