如何从公共api请求文件向redux发送数据



我创建了一个通用的js文件来调用服务请求。我想将提取的数据存储在我的redux管理存储中。但我收到了这个错误,说Invalid hook call. Hooks can only be called inside of the body of a function component.,我想这是因为我没有为这个文件使用react原生样板文件。但问题是我不想,我只想提出服务请求和响应。

import { useDispatch } from "react-redux";
import { addToken } from "../redux/actions/actions";
const { default: Axios } = require("axios");
const dispatch = useDispatch();   
const handleResponse=(response, jsonResponse)=> {
// const dispatch = useDispatch(); //-----also tried using dispatch here
const jsonRes = jsonResponse;
const { status } = response;
const { errors } = Object.assign({}, jsonRes);
const resp = {
status,
body: jsonResponse,
errors,
headers: response.headers,
};
console.log(resp, 'handle response');
return await dispatch(addToken(resp.body.token))
};
const API = {
makePostRequest(token) {
Axios({
url: URL,
...req,
timeout: 30000
}).then(res => 
console.log('going to handle');
await handleResponse(res, res.data)
})
}
export default API

我知道会有一些简单的方法,但我不知道

不要从react-redux使用useDispatch,而是从redux使用dispatch。您需要在应用程序中使用redux-thunk

看看这篇文章中的例子Redux Thunk用例子解释

本文还提供了一个如何将redux用于异步调用(在您的情况下为axios请求(的示例。

我建议重构你的api来区分两件事:

  1. fetcher-它将调用您的api,例如通过axios,并在Promise中返回数据
  2. redux操作创建者(thunk,请参阅文章中的示例(-它将(可选(调度REQUEST_STARTED,然后调用您的fetcher,最后将调度(REQUEST_SUCCESS/REQUEST_FAILURE(操作

您将在react组件中调用后一个redux操作创建者,在那里您将调度它(例如使用useDispatch(

最新更新