【发布时间】:2018-04-18 19:51:15
【问题描述】:
假设我有这些 Flux 操作;
{
"type": "USER_LOADED",
"payload": { ... }
}
{
"type": "USER_LOAD_FAILED",
"payload": { ... }
}
{
"type": "SHOW_ERROR_MODAL",
"payload": { ... }
}
{
"type": "HIDE_ERROR_MODAL"
}
我有一个UserStore(监听USER_LOADED 和USER_LOAD_FAILED 并相应更新)和一个ModalStore(监听SHOW_ERROR_MODAL 并相应更新)。
我有一个始终出现在页面上的Modal 组件,它呈现来自ModalStore 的内容。
当USER_LOAD_FAILED 发生时显示错误模式的最佳方式是什么?应该由ModalStore听吗?我最终会得到很多不同类型的 *_LOAD_FAILED 操作,这是个好主意吗?
我无法从UserStore 发送回复USER_LOAD_FAILED,因为您无法在发送期间发送。
我可以从一些“控制器”组件中调度,该组件按照这些方式执行某些操作;
class UserController extends PureComponent {
constructor(...args) {
super(...args);
this.state = { error: null, notified: false };
}
componentDidMount = () => this.props.flux.store('UserStore').on('change', this.onUserChange)
componentDidUpdate = () => {
if (this.state.error && !this.state.notified) {
this.props.flux.actions.showErrorModal(this.state.error);
this.setState({ notified: true });
}
}
componentWillUnmount = () => this.props.flux.store('UserStore').off('change', this.onUserChange)
onUserChange = () => {
const userStore = this.props.flux.store('UserStore');
// UserStore#getError() returns the most recent error which occurred (from USER_LOAD_FAILED).
const error = userStore.getError();
this.setState({ error, notified: error !== this.state.error });
}
render = () => ...
}
但我觉得这只是一种解决方法,而不是实际的解决方案。
我想到的最后一种方法是在最初发送 USER_LOAD_FAILED 的动作创建者中发送 SHOW_ERROR_MODAL,但我仍然不知道这是否是“建议”方式,因为您最终可能会提出其他情况下有很多逻辑。
【问题讨论】:
标签: reactjs flux reactjs-flux