在功能组件中反应承诺 [英] react promise in functional component
问题描述
我有一个功能组件,我想在其中将数据保存在我的输入表单中,并使用 saveForm 方法将它们发送到我的 Java API.
I have a functional component in which I want to save the data in my inputs form sending them with saveForm method to my java API.
我怎样才能读取这个承诺的响应 props.saveForm(为了寻找潜在的服务器错误)在功能组件中?我读到在这些情况下必须使用 useEffect 钩子..>
请赐教.谢谢你的智慧.
How can I read the response of this promise props.saveForm (in order to look for potentials server errors) in a functional component? I've read that in these cases it must be used useEffect hooks..but If I move my handleSubmitForm() inside useEffect than I can't call it when the onSubmit event is thrown.
我在其他问题中找到的代码:
Please enlight me. Thank you for your wisdom.
Code I found in others questions :
我现在的代码:
My code right now:
);
actions.js:
actions.js:
export const saveForm= (newData) => async (dispatch) => {
try {
const res = await axios.post("/api/formexample", newData);
dispatch({//this dispatch is to clean past errors if now are resolved
type: GET_ERRORS,
payload: {},
});
} catch (err) {
dispatch({
type: GET_ERRORS,
payload: err.response.data,
});
}
};
推荐答案
您不必将 handleSubmitForm
放在 useEffect
中.此函数用于响应按钮点击,因此它不是效果.
You don't have to put your handleSubmitForm
in a useEffect
. This function is being used in response to a button click, so it's not an effect.
您可以使您的函数 handleSubmitForm
异步并执行等待.
You can make your function handleSubmitForm
async and do an await.
const handleSubmitForm = async (e) => {
e.preventDefault();
const result = await callValidation(data));
// check your result
};
我不确定您是如何检查验证的,所以这只是一个示例.
I'm not sure how you are checking your validation, so this is just an example.
这篇关于在功能组件中反应承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!