简体   繁体   English

this.forceUpdate()重构withHandler

[英]this.forceUpdate() in recompose withHandler

I want to use this.forceUpdate() in one of the handler named 'update' in withHandlers of my compose. 我想在我的this.forceUpdate()中的一个名为'update'的处理程序中使用this.forceUpdate() I am using recompose to achieve the same. 我正在使用重构来实现同样的目标。 Find sample code below: 查找以下示例代码:

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

But it is not working. 但它没有用。 Does anyone know how to use forceUpdate() method of react in withHandlers of recompose library? 有谁知道如何在重构库的withHandlers中使用forceUpdate()方法?

Is there any alternative to achieve same result as forceUpdate() ? 有没有替代方法forceUpdate()forceUpdate()相同的结果?

You're using this outside of your component's scope, so this is undefined. 您使用this您的组件的范围之外,所以this是不确定的。

I don't know what do you want to achieve but you should try another way to do it. 我不知道你想要实现什么,但你应该尝试另一种方式来实现它。

Normally you should try to avoid all uses of forceUpdate() 通常你应该尽量避免使用forceUpdate()

There's forceUpdate in lifecycle. 生命周期中有forceUpdate。

We use it like this: 我们这样使用它:

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;

This make a higher-order component that forces update when the model fires change event. 这使得高阶组件在模型触发更改事件时强制更新。

You can use withState to make your own props.forceUpdate , since all state updaters trigger the component to re-render. 您可以使用withState创建自己的props.forceUpdate ,因为所有状态更新程序都会触发组件重新呈现。

IE: IE:

withState('_forceUpdate', 'forceUpdate')

Then call props.forceUpdate() wherever. 然后在任何地方调用props.forceUpdate()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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