如何使用 React Query 将关键字搜索到 api

How to search keyword into api with React Query

如何将参数中的“关键字”用于我的 axios get 请求? 我的方法无效,

//前端代码

const ComprasLista = () => {
  const { keyword } = useParams();
  

  const compras = useQuery("compras", ({ keyword = "" }) => {
    return axios
      .get(`https://582821e.sse.codesandbox.io/api/compras?keyword=${keyword}`)
      .then((res) => res.data);
  });

  
  // 
};

export default ComprasLista;

//后端代码

router.get(
  "/",
  asyncHandler(async (req, res) => {
    const keyword = req.query.keyword
      ? {
          fornecedor: {
            $regex: req.query.keyword,
            $options: "i"
          }
        }
      : {};
    const compras = await Compras.find({ ...keyword });
    res.json(compras);
  })
);

您查询的参数应该转到您的 queryKey,然后传递给您的查询函数:

const fetchCompras = ({ queryKey: [,keyword] }) => {
    return axios
      .get(`https://582821e.sse.codesandbox.io/api/compras?keyword=${keyword}`)
      .then((res) => res.data);
  })

const ComprasLista = () => {
  const { keyword } = useParams();
  
  const compras = useQuery(["compras", keyword], fetchCompras);
 
};

当然你也可以关闭它,但重要的是将它放入查询键中,这样你就可以在键更改时自动重新获取:

const ComprasLista = () => {
  const { keyword } = useParams();
  
  const compras = useQuery(["compras", keyword], () => {
    return axios
      .get(`https://582821e.sse.codesandbox.io/api/compras?keyword=${keyword}`)
      .then((res) => res.data);
    })
  });
 
};