2017-10-21 31 views
1

showing a toast「敬酒」應該在Mobx State Tree中居住?

我的異步操作往往是這個樣子:

anAsyncAction: process(function* anAsyncAction() { 
    self.isLoading = true; 
    const service = getEnv<IMyMarksPageStoreEnv>(self).myService; 
    try 
    { 
     yield service.doSomething(); 
    }   
    finally 
    { 
     self.isLoading = false; 
    } 
}), 

然後我讓視圖處理什麼祝酒顯示:

toaster = Toaster.create({ 
    position: Position.TOP 
}); 

render() { 
    return <button disabled={this.props.store.isLoading} onClick={this.handleButtonClicked}>Do Async Thing</button> 
} 

handleButtonClicked =() => { 
    const store = this.props.store; 
    try 
    { 
     await store.anAsyncAction(); 
     toaster.show({ message: "Saved!", intent: Intent.SUCCESS }); 
    } 
    catch(e) 
    { 
     toaster.show({ message: "Whoops an error occured: "+e, intent: Intent.DANGER }); 
    } 
} 

但是我開始覺得祝酒詞處理應該存在於商店的異步嘗試中,而不是視圖,但是它的混合業務邏輯與視圖,所以我不知道。

有什麼建議嗎?

回答

0

猜測這不是特定於mobx或mobx-state-tree,但我可能會考慮在圖片中添加一個專用的NotificationStoreService try/catch/finally將成爲通知的一個生產者,其來源爲service,另一個可能是源自transport的fetch/xhr包裝。 決定如何呈現/處理這些將由業務邏輯決定。

+0

你能否在你的回答中澄清一點點w或許參考了我的示例代碼,您是否指「一個通知的生產者」? – mikeysee

1

我認爲消息應用程序的一部分。 在我的應用我有根級別陣列

export default types.model('AppStore', { 
    .... 
    flashMessages: types.optional(types.array(FlashMessage), []), 
}) 
    .actions((self) => { 
    /* eslint-disable no-param-reassign */ 
    const addFlashMessage = (message) => { 
     self.flashMessages.push(FlashMessage.create({ 
     ...message, 
     details: message.details.toString(), 
     })); 
    }; 

    function addErrorMessage(text, details = '') { 
     addFlashMessage({ type: 'error', text, details }); 
    } 

    function addInfoMessage(text, details = '') { 
     addFlashMessage({ type: 'info', text, details }); 
    } 

    function addSuccessMessage(text, details = '') { 
     addFlashMessage({ type: 'success', text, details }); 
    } 

然後

@inject('appStore') 
@observer 
class App extends Component { 
    render() { 
    const app = this.props.appStore; 

    return (
     <BlockUI tag="div" blocking={app.blockUI}> 
     <Notifications messages={app.unseenFlashMessages} /> 
    ... 

,且在組件

this.props.appStore.addSuccessMessage(`User ${name} saved`); 

這也將讓你實現一個「最後5個消息」如果你錯過了一個可能有用的東西

+0

哦,那很有趣,謝謝。你如何去除看不見的Flash消息?你的render()過程中? – mikeysee

+1

我在這個項目中使用了'material-ui',所以我的消息是'Snackbar',它有一個帶有自動隱藏和回調的'close'回調函數(Toastr有'toastr.options.onHidden'。 message.setSeen(真)' –