[英]Dispatch not sending the action to the reducer
I have a react redux app and I am having an issue with dispatching the action to the reducer.我有一个反应 redux 应用程序,我在将操作分派给减速器时遇到问题。 This is what I have in my actions.js这就是我的 actions.js
import GetDataFromAPIs from "../utils/api-data";
export const UPDATE_DATA = 'UPDATE_DATA';
export const updateData = async => {
const newData = await GetDataFromAPIs();
return{
type: UPDATE_DATA,
payload: newData
};
};
and this is how I am calling updateData from index.js:这就是我从 index.js 调用updateData的方式:
const menuStore = createStore(MyReducer, composeWithDevTools(applyMiddleware(thunk)));
menuStore.dispatch(applyMiddleware(thunk)(updateData));
I can step through the actions.js but I don't see menuStore.dispatch sending the action to the reducer.我可以单步执行actions.js,但我没有看到menuStore.dispatch 将操作发送到reducer。 What am I missing?我错过了什么?
When using thunk middleware you need to pass the 'thunk' to the dispatch function.使用 thunk 中间件时,您需要将“thunk”传递给调度 function。
First, the thunk need some modification.首先,thunk 需要一些修改。 As the docs say here正如文档所说here
A thunk is a function that wraps an expression to delay its evaluation thunk 是 function 包装表达式以延迟其评估
Therefore need to change the thunk as below.因此需要如下改变thunk。
export const updateData = async (dispatch)=> {
const newData = await GetDataFromAPIs();
dispatch({
type: UPDATE_DATA,
payload: newData
});
};
Now pass this thunk to the store.dispatch()
function.现在将此 thunk 传递给store.dispatch()
function。
menuStore.dispatch(updateData);
menuStore.dispatch(updateData())
not just passing reference还需要在调度menuStore.dispatch(updateData())
中调用该操作,而不仅仅是传递引用export const updateData = inputData => async dispatch => {
const newData = await GetDataFromAPIs();
dispatch({
type: UPDATE_DATA,
payload: newData
})
};
Usage用法
menuStore.dispatch(updateData())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.