gpt4 book ai didi

mobx - "Toasts"应该位于 Mobx 状态树中的什么位置?

转载 作者:行者123 更新时间:2023-12-05 05:19:02 29 4
gpt4 key购买 nike

showing a toast

我的异步操作看起来像这样:

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

然后我让 View 处理要显示的 toast :

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 });
}
}

但我开始认为 toasts 处理应该存在于商店的异步 try-catch 中而不是 View 中,但是它随后将业务逻辑与 View 混合在一起,所以我不确定。

有什么建议吗?

最佳答案

我认为消息应用程序的一部分。在我的应用程序中,我在根级别有一个数组

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 条消息”之类的东西,如果您错过了一个目标,这可能会有用

关于mobx - "Toasts"应该位于 Mobx 状态树中的什么位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46859238/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com