在这篇文章中,我展示了一个很好用的useFetch(GET)函数:How to return REST Status Code from React Hook call to API Endpoint?
我尝试修改该代码以处理POST请求。这是我到目前为止的内容:
/**
It dds * POST data to endpoint with AWS Access Token
* @param {string} url The full path of the endpoint to post to
* @param {JSON} body The payload sent with the POST request
* @param {object} options The AWS Access token, wrapped as a header
*/
export const useFetchPost = (initialUrl, body) => {
const [url, setUrl] = useState(initialUrl);
const { appStore } = useContext(AppContext);
const [state, dispatch] = useReducer(dataFetchReducer, {
isLoading: false,
isError: false,
});
useEffect(() => {
let didCancel = false;
const options = appStore.awsConfig;
const fetchDataPost = async () => {
dispatch({ type: 'FETCH_INIT' });
try {
let response;
if (url && options) {
response = await axios.post(url, body, options);
}
if (!didCancel) {
dispatch({ type: 'FETCH_SUCCESS', payload: response.data });
}
} catch (error) {
// We won't force an error if there's no URL
if (!didCancel && url !== null) {
dispatch({ type: 'FETCH_FAILURE' });
}
}
};
fetchDataPost();
return () => {
didCancel = true;
};
}, [url, body, appStore.awsConfig]);
return [state, setUrl];
};
它不接受实例化该函数的代码(模拟我对useFetch
所做的操作:
const [{ isLoading, isError }, doFetchPost] = useFetchPost(
null,
{ }
);
这是我得到的消息:“警告:状态从useState()和useReducer()进行更新Hooks不支持第二个回调参数。要在渲染后执行副作用,请在组件主体中使用useEffect声明它()。”然后继续无休止地呼叫我的端点。
有人可以共享一个useFetchPost
类型的功能,该功能可以存在于单独的文件中,并可以在我的React组件中导入并使用吗?