比如有这么一个场景:我用antd的message组件https://ant.design/components/message/ ,这个组件是用js调用的方式而非标签实现的,我需要在登陆成功后显示一条提示信息,如果我是用redux-thunk,那么我可以再dispatch后执行Promise的then来执行相关的代码,而用dva的话,这段逻辑貌似我只能写在effects里面,能有不那么耦合的方式来做类似这种处理么?(当然很大原因都是因为我对于redux-saga的不熟悉)
还有另外一个问题就是,我需要在登出的时候重置所有的model为初始state,以前用传统写法的话我可以封装一个方法来做这个处理,因为我可以在reducers中判断是不是action.type 为 logout,而在现在的时候因为你都用了namespace,所以我没找到一个能够通用的方式来做这个动作,总不能在logout请求完成后把每个model下对应namespace的lougout effect都执行一遍吧。。?
@sorrycc 你好,请问在组件内部通过dispatch的方式调用 effect ,有没有什么方式直接在组件内部绑定 effect 执行完的回调?有些场景我不需要修改 model ,比如:
@CodingMonkeyzh
这个问题已经有不少人有反馈了,但目前没啥优雅的方案。可以用 action 中加回调的方式:(大家都这么做)
dispatch({
type: '',
onComplete() {},
});
然后 onComplete 要在 effect 里调用下。
*effect(action) {
// 在合适的地方调用 action.onCOmplete
action.onComplete();
}
之后会尝试让 effect 的返回 promise,比如:dispatch(action).then()。
dispatch({
type: 'user/create',
payload: values,
onComplete(){},
}).then(console.log('xxx'));
菜鸟求助,上面的写法报错,then不是个function.请问为什么呢?
我又应该如何实现表单提交后服务器校验错误及时反馈在表单上呢?
谢谢.
@IveChen @sorrycc @CodingMonkeyzh
@xjdata dispatch 没有返回 promise,所以写在 onComplete 里吧。
@sorrycc 呃... 不好意思在问下.
dispatch({
type: 'user/create',
payload: values,
onComplete(){
console.log('xxx');//这句不执行.请求肯定完成了,服务器端也返回了错误原因的数组. 但是 onComplete 无法执行
},
})
我用的还是1.1, 因为1.2的动态路由问题.... 和版本有关系吗? 要是1.2的特性,那就等过段时间在说也行.
和版本无关,onComplete 要在 effect 里调用下的。
*effect(action) {
// 在合适的地方调用 action.onCOmplete
action.onComplete();
}
@sorrycc 谢谢,已解决.
其实也可以在 dispatch 外包一层promise,把resolve 传进effect 里。控制流程
new Promise((resolve, reject) => {
this.props.dispatch({
type: 'upload/postNote',
payload: {
username: this.props.username,
text: this.props.text,
fileList: this.props.fileList,
resolve: resolve
}
});
}).then(() => {
socket.emit('message', this.props.username, () => {
message.info(${this.props.username} 有新动态);
});
})
类似这样。
计划什么时候dispatch支持promise呢。 比如在页面里面
dispatch({
type,
payload,
}).then(successFn)
effect里面
*getSomeThing({payload}, {put}, resolve) {resolve()} 这样。
Most helpful comment
计划什么时候dispatch支持promise呢。 比如在页面里面
dispatch({ type, payload, }).then(successFn)effect里面
*getSomeThing({payload}, {put}, resolve) {resolve()}这样。