2017-10-21 131 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(真)' –