英文:
The function (dispath) does not work when I press the button
问题
这是一个与Redax一起使用的操作函数(它完全正常工作,因为我使用它)
export const fetchCategory = () => {
return async (dispatch) => {
try {
dispatch(settingsSlice.actions.settingsFetching());
const response = await request("/category/getAll", "POST", {});
dispatch(settingsSlice.actions.settingsFetchingSuccess(response));
} catch (e) {
dispatch(settingsSlice.actions.settingsFetchingError(e));
}
};
};
我需要在按下按钮时发出请求并更新状态。以下是单击按钮时执行的函数:
const buttonHandler = async () => {
await request("/category/create", "POST", {
newCategory: {
label: form.categoryLabel,
limit: form.categoryLimit,
},
});
setForm(initialState);
fetchCategory();
};
我已经检查了,表单已发送到后端,一切正常,除了这个 "fetchCategory"。
我已经尝试使用 useEffect:
useEffect(() => {
fetchCategory();
}, [Button, buttonHandler]);
我尝试安装不同的依赖项,但没有结果。如何解决这个问题?
英文:
Its a action-function that works with redax (it works perfectly because I used it)
export const fetchCategory = () => {
return async (dispatch) => {
try {
dispatch(settingsSlice.actions.settingsFetching());
const response = await request("/category/getAll", "POST", {});
dispatch(settingsSlice.actions.settingsFetchingSuccess(response));
} catch (e) {
dispatch(settingsSlice.actions.settingsFetchingError(e));
}
};
};
I need that when the button is pressed, a request is made to the server and the state is updated
Here is the function that is executed when you click on the button :
const buttonHandler = async () => {
await request("/category/create", "POST", {
newCategory: {
label: form.categoryLabel,
limit: form.categoryLimit,
},
});
setForm(initialState);
fetchCategory();
};
I checked, the form is sent to the backend and everything works fine except for this "fetchCategory"
I already tried to do this using useEffect
useEffect(() => {
fetchCategory();
}, [Button , buttonHandler]);
i tried to install different dependencies but no result. How can this problem be fixed?
答案1
得分: 0
你需要“dispatch”这个动作!
你的fetchCategory
函数是一个“thunk动作创建者”。调用fetchCategory()
会创建thunk动作,但不会执行它。你需要调用dispatch(fetchCategory())
来执行这个动作。
英文:
You need to dispatch
the action!
Your fetchCategory
function is a "thunk action creator". Calling fetchCategory()
creates the thunk action, but doesn't do anything with it. You need to call dispatch(fetchCategory())
to execute the action.
const buttonHandler = async () => {
await request("/category/create", "POST", {
newCategory: {
label: form.categoryLabel,
limit: form.categoryLimit,
},
});
setForm(initialState);
--> dispatch(fetchCategory()); <--
};
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论