簡體   English   中英

僅在React中另一個函數完成運行時才調用函數

[英]Calling a function only when another function finishes running in React

我有一個遵循Flux數據模式的函數,我這樣稱呼它

UserService.createNewUser(data);

一旦創建用戶的函數完成執行,我想運行另一個遵循相同數據模式的函數:

NextService.createNewMessage(data);

我如何設置它,以便僅在UserService完成運行后才調用NextService

用戶商店:

getUser: function() {
    return User;
  },
addChangeListener: function(callback) {
    this.on(CHANGE_EVENT, callback);
  },
  removeChangeListener: function(callback) {
    this.removeListener(CHANGE_EVENT, callback);
  }

聽完更改后,我致電:

if (UserStore.getUser()) {
// in here is where I run NextService.createNewMessage(data); 
}

但是,在createNewUser完成之前將調用UserStore

如果您遵循通量模式,那么我假設這些服務具有addChangeListener函數? 如果是這樣,我建議在您的調用NextService的組件中添加一個更改偵聽器,例如:

class YourComponent extends React.Component{
    constructor(props){
        super(props);
        this._handleStoreChange = this.handleStoreChange.bind(this);
    }
    handleStoreChange(data){
        NextService.createNewMessage(data);
    }
    componentDidMount(){
        UserService.addChangeListener(this._handleStoreChange);
    }
    componentWillUnmount(){
        UserService.removeChangeListener(this._handleStoreChange);
    }
    render(){
        return (
            <h1>hello</h1>
        );
    }
}

暫無
暫無

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

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