简体   繁体   中英

this.forceUpdate() in recompose withHandler

I want to use this.forceUpdate() in one of the handler named 'update' in withHandlers of my compose. 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?

Is there any alternative to achieve same result as forceUpdate() ?

You're using this outside of your component's scope, so this is undefined.

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

There's forceUpdate in lifecycle.

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.

IE:

withState('_forceUpdate', 'forceUpdate')

Then call props.forceUpdate() wherever.

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