我想将HTTP操作放在存储区中而不是组件中,这将面临问题。我想在HTTP错误后弹出烤面包,该错误应由组件处理。 我想知道我该怎么办。谢谢
这是我的假密码。 https://codesandbox.io/s/j4m351ryw
// store
@action.bound
async updateCount(_count, callback) {
this.count = _count;
try {
// call http service
const response = await MyService();
if (response.error) {
callback(response.error);
}
} catch (error) {
callback(error);
}
}
// component
click = () => {
const store = this.props.store;
// The way we do it now
// Is there a better way to handle it
store.updateCount(3, err => {
if (err) {
alert("error");
}
});
};
答案 0 :(得分:0)
您可以通过以下方式解决这种情况:
// store
@observable updateError = null;
@action.bound
async updateCount(_count, callback) {
this.count = _count;
try {
// call http service
const response = await MyService();
if (response.error) {
this.updateError = response.error;
}
} catch (error) {
this.updateError = error;
}
}
// component
click = () => {
this.props.store.updateCount(3);
};
render() {
if (this.props.store.updateError) {
return <h1>Error happened during update. Details {this.props.store.updateError}<h1>
}
return <YourComponent/>
}
这种解决方案的优势在于,您可以将业务逻辑和组件逻辑分开,并且不将业务逻辑与组件事件处理程序代码混合在一起。