简体   繁体   English

如何在Redux中从诺言中调度动作?

[英]How to dispatch an action from a promise in redux?

I need to dispatch an action from a promise in redux when it is resolved. 解决后,我需要从redux中的一个Promise调度一个动作。 I tried with the following code (commented out) with no success. 我尝试使用以下代码(注释掉)没有成功。

Could you please point me out in the right direction? 您能指出我正确的方向吗?

Error I get is: 我得到的错误是:

ReferenceError: dispatch is not defined ReferenceError:调度未定义

 const getLocations = (query:string):ActionType => { const value = query.trim() if (!value.length) { return ({ type: null, payload: null }) } return ({ type: types.GET_LOCATIONS, payload: new Promise((resolve, reject) => { fetch(api.find(query)).then(response => { resolve(response.json()) // dispatch(myAction()) }) }) }) } 

You need middleware to catch the promise, try redux 您需要中间件来兑现承诺,请尝试redux

https://www.npmjs.com/package/redux-promise https://www.npmjs.com/package/redux-promise

//index.js 
import { createStore, applyMiddleware } from 'redux';
import reduxPromise from 'reduxPromise';

const store = createStore(reducers,  applyMiddleware(reduxPromise)));

ReactDOM.render(
<Provider store={store}>
    <App />
</Provider>
, rootEl );

then in your action return the promise 然后在你的行动中返回诺言

return ({
   type: GET_LOCATIONS,
   payload: fetch(api.find(query))
})

you can google search the rest, I wrote this quickly. 你可以谷歌搜索其余的,我很快就写了。 I do my then reaction to the response in my reducer 我对减速器中的响应做出反应

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM