重新组合withState如何更新道具变更 [英] recompose withState how to update on props changes

查看:128
本文介绍了重新组合withState如何更新道具变更的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个尝试修改的高阶组件(我不熟悉重组).

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

这就是我的组件:

<Map mycenter={mycenter}  />

如果mycenter已更新,我希望地图组件更新或重新渲染.我正在尝试从中修改代码 https://github.com/istarkov/google-map-thousands-markers/blob/master/src/Map.js

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

我对代码进行了一些修改.首先,将地图中心设置为mycenter.那行得通.

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 });
    },

是否有一种方法可以在更新"mycenter"时重新发布组件或更新中心?

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

推荐答案

当前,最好的方法是使用生命周期. 初始状态(({ mycenter }) => ({ center:mycenter, zoom: 12 }))的回调仅发生一次.

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 }})
    }
  })
)

这篇关于重新组合withState如何更新道具变更的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆