我正在尝试学习 react 查询并遵循了很多指南。然而,每次我尝试使用参数时都会出现问题。 我下面的这段代码一直告诉我,即使 console.log(id) 打印出正确的数字,也无法读取未定义的属性(读取“id”)。
const PracticeList = ({id}) => {
const idTest = id
conosole.log(idTest) //this prints 190 and is not undefined
const { isLoading, isFetching, data, isError } = useQuery(["list",{id:idTest}],GetList,{
retry:1,
retryDelay:500
})
if (isLoading) {
return <p>Loading</p>
}
if (isError) {
return <p>Error getting posts...</p>
}
return (
<div> {isFetching && <p>Updating</p>}{data &&<p>{data.lists}</p>}</div>
)
}
export const GetList = async(key,obj)=>{
console.log(key,obj) //This prints that key is defined but obj is undefined?
const {data} = await ShoppingListAPI.get(`/getShoppingList`,{id:obj.id});
return data;
}
这种情况从未真正发生过,因为它以前崩溃过,但我确实知道它可以通过 postman 工作。
import axios from 'axios';
export default axios.create({
baseURL:"http://localhost:3005/api/v1/",
});
这是我设置 Id 的地方。
import './App.css';
import {Container, Typography} from '@mui/material'
import AllLists from './AllLists';
import { useState } from 'react';
import ShoppingList2 from './ShoppingList2';
import Practice from './Practice';
import PracticeList from './PracticeList';
function App() {
const [activeList, setActiveList]= useState(190)
return (
<div className="App">
<Typography>Shopping list</Typography>
<Container maxWidth="lg">
<Practice/>
{activeList&&<PracticeList id={activeList}/>}
</Container>
</div>
);
}
export default App;
最佳答案
从 v3 开始,react-query 将一个名为 QueryFunctionContext 的对象注入(inject)到 queryFn 中。它包含 queryKey 以及其他信息。
因此,如果您的查询是:
useQuery(["list",{id:idTest}],GetList)
您可以通过以下方式提取GetList
中的queryKey:
const GetList = (queryFunctionContext) => {
const queryKey = queryFunctionContext.queryKey
}
queryKey[0]
将是 "list"
并且 queryKey[1]
应该是包含 id 的对象
.
关于javascript - React-query 返回无法读取未定义的属性,即使我可以看到 id 已设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72038425/