![](/img/trans.png)
[英]ApolloClient useQuery onError callback doesn't return errors
[英]useQuery doesn't return the data and the function is returned
我正在尝试使用 react-query(useQuery) 获取我的应用程序中的聊天列表。 我的 API 调用在不同的组件中,我正在使用 Axios 来获取数据。 但是组件返回的是 function 本身而不是数据。哪个部分是错误的?
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: [],
});
};
}
我建议您稍微重构一下代码以解决您的一些问题:
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();
// ...
}
或者,如果您确实想像使用 function 一样使用getContacts
,那么就不要将它包装在useQuery
中,因为这会将它变成一个钩子。
async function getUserData() {
const data = await getContacts()
// ...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.