【问题标题】:this.forceUpdate() in recompose withHandlerthis.forceUpdate() 中的 recompose withHandler
【发布时间】:2018-07-29 14:20:21
【问题描述】:

我想在我撰写的 withHandlers 中名为“update”的处理程序之一中使用this.forceUpdate()。我正在使用 recompose 来实现相同的目的。在下面找到示例代码:

const abc = compose(
    withHandlers(
      update: () => () => this.forceUpdate()
    )
)

但它不起作用。有谁知道如何在 recompose 库的 withHandlers 中使用 forceUpdate() 反应方法?

有没有其他方法可以达到与forceUpdate() 相同的结果?

【问题讨论】:

    标签: reactjs recompose


    【解决方案1】:

    您可以使用withState 来创建自己的props.forceUpdate,因为所有状态更新程序都会触发组件重新渲染。

    IE:

    withState('_forceUpdate', 'forceUpdate')
    

    然后在任何地方拨打props.forceUpdate()

    【讨论】:

      【解决方案2】:

      生命周期中有 forceUpdate。

      我们这样使用它:

      import { lifecycle } from 'recompose';
      
      const listensForChangingModel = ( propName='model' ) => lifecycle( {
              componentDidMount() {
                      this.onModelChanged = () => this.forceUpdate();
      
                      this.props[ propName ].on( 'change', this.onModelChanged );
              },  
              componentWillUnmount() {
                      this.props[ propName ].off( 'change', this.onModelChanged );
              },  
              componentDidUpdate( prevProps ) { 
                      if ( prevProps[ propName ].cid !== this.props[ propName ].cid ) { 
                              prevProps[ propName ].off( 'change', this.onModelChanged );
                              this.props[ propName ].on( 'change', this.onModelChanged );
                      }   
              },  
      } );
      
      export default listensForChangingModel;
      

      这会产生一个高阶组件,当模型触发更改事件时强制更新。

      【讨论】:

        【解决方案3】:

        您在组件范围之外使用this,因此this 未定义。

        我不知道你想达到什么目的,但你应该尝试另一种方式来实现它。

        通常你应该尽量避免使用 forceUpdate()

        【讨论】:

        • 你是对的,我知道“this”的范围超出了我的组件。我的问题是,如何让它进入内部。当我使用 compose 时,我有一个 compose() 和一个与 compose 一起使用的普通函数来制作组件。现在,我该如何使用 forceUpdate()。似乎找不到任何关于此的信息。
        • @ShyamKansagra 您需要声明一个与withHandlers 一起使用的 HOC,我认为这不是您想要的,您想在什么事件上强制更新?
        • 早些时候,当我有简单的 class xyz extends abc component{} 结构时,我在里面使用了 this.forceUpdate() 并且它正在工作。现在我已经将我的类组件转换为组合组件,只是不知道如何复制 forceUpdate。众所周知,我们在类中定义的所有方法现在都需要在 withHandlers() 中定义。但是我们如何转换 forceUpdate() 呢?这就是我被困的地方。
        • 不确定,但您是否尝试过使用 props 代替?像这样:update: props => () => props.forceUpdate()
        • 刚才试过了,不行。说 forceUpdate() 不是一个函数。我已经将 ({ a, b}) 作为道具传递。如何在这里使用 forceUpdate() ?我试过 {a,b}.forceUpdate(),没用。
        猜你喜欢
        • 2017-10-26
        • 2019-12-18
        • 2019-05-24
        • 2018-11-30
        • 2016-10-17
        • 2017-08-09
        • 1970-01-01
        • 2018-05-21
        • 2019-02-21
        相关资源
        最近更新 更多