簡體   English   中英

this.forceUpdate()重構withHandler

[英]this.forceUpdate() in recompose withHandler

我想在我的this.forceUpdate()中的一個名為'update'的處理程序中使用this.forceUpdate() 我正在使用重構來實現同樣的目標。 查找以下示例代碼:

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

但它沒有用。 有誰知道如何在重構庫的withHandlers中使用forceUpdate()方法?

有沒有替代方法forceUpdate()forceUpdate()相同的結果?

您使用this您的組件的范圍之外,所以this是不確定的。

我不知道你想要實現什么,但你應該嘗試另一種方式來實現它。

通常你應該盡量避免使用forceUpdate()

生命周期中有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;

這使得高階組件在模型觸發更改事件時強制更新。

您可以使用withState創建自己的props.forceUpdate ,因為所有狀態更新程序都會觸發組件重新呈現。

IE:

withState('_forceUpdate', 'forceUpdate')

然后在任何地方調用props.forceUpdate()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM