我正在嘗試使用 react-query(useQuery) 獲取我的應用程式中的聊天串列。我的 API 呼叫位于不同的組件中,我正在使用 Axios 獲取資料。但組件回傳的是函式本身而不是資料。哪一部分是錯誤的?
import { useQuery } from "react-query";
import axios from "axios";
const getContacts = async () => {
const headers = { Authorization: localStorage.getItem("token") };
const options = {
method: "GET",
url: "http://127.0.0.1:8000/chat/mine/",
headers: headers,
};
const { data } = await axios.request(options);
return data;
};
function GetUserDataUseQuery() {
return useQuery("getContacts", getContacts);
}
export default GetUserDataUseQuery;
function getUserData() {
const data = GetUserDataUseQuery;
return (dispatch) => {
dispatch({
type: GET_CONTACTS,
payload: [],
});
};
}
uj5u.com熱心網友回復:
我建議您稍微重構一下代碼以解決一些問題:
const getContacts = async () => { /*...*/ }
const useGetContacts = () {
return useQuery('getContacts', getContacts)
}
// `useGetContacts` is a hook, so it should be called inside of a
// component or another hook - you *cannot* call a hook inside of a
// simple function, which is what you're attempting to do inside `getUserData`
function MyComponent() {
const contacts = useGetContacts();
// ...
}
或者,如果您確實想將getContacts其用作函式,則只需不要將其包裝在 a 中useQuery,因為這會將它變成一個鉤子。
async function getUserData() {
const data = await getContacts()
// ...
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/398177.html
標籤:javascript 反应 接口 公理 反应查询
上一篇:如何將SWR與泛型T一起使用?
