Redux工具包RTK查询发送查询参数正在返回未定义

发布于 2025-01-17 17:44:20 字数 2664 浏览 0 评论 0原文

如何使用 Redux Toolkit RTK 查询将查询参数传递到 api,而不使其未定义?

import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";

const cryptoApiHeaders = {
  "X-RapidAPI-Host": "...",
  "X-RapidAPI-Key": "...",
};

const baseUrl = "...";

const createRequest = (url) => ({ url, headers: cryptoApiHeaders });

export const cryptoApi = createApi({
  reducerPath: "cryptoApi",
  baseQuery: fetchBaseQuery({ baseUrl }),
  endpoints: (builder) => ({
    getCryptos: builder.query({
      query: (name) => createRequest(`/coins?limit=${name}`),
    }),
  }),
});

export const { useGetCryptosQuery } = cryptoApi;

当我从组件向下传递参数时,它要么不传递,要么似乎无法识别它,因为它总是显示未定义 https://.../coins?limit=undefined。我真的不知道我做错了什么。

import React, { useState } from "react";
import millify from "millify";
import { Link } from "react-router-dom";
import { Card, Row, Col, Input } from "antd";

import { useGetCryptosQuery } from "../services/cryptoApi";

const Cryptocurrencies = () => {
  const count = 10;
  const { data: cryptosList, isFetching } = useGetCryptosQuery(count);
  const [cryptos, setCryptos] = useState(cryptosList?.data?.coins);

  return (
    <>
      <Row gutter={[32, 32]} className="crypto-card-container">
        {cryptos.map((currency) => (
          <Col xs={24} sm={12} lg={6} className="crypto-card" key={currency.id}>
            <Link to={`/crypto/${currency.uuid}`}>
              <Card
                extra={
                  <img
                    className="crypto-image"
                    src={currency.iconUrl}
                    alt={`${currency} currency`}
                  />
                }
                title={`${currency.rank}. ${currency.name}`}
                hoverable
              >
                <p>Price: {millify(currency.price)}</p>
                <p>Market Cap: {millify(currency.marketCap)}</p>
                <p>Daily Change: {millify(currency.change)}%</p>
              </Card>
            </Link>
          </Col>
        ))}
      </Row>
    </>
  );
};

export default Cryptocurrencies;

我尝试通过将值直接放入查询中来对其进行硬编码,并且它工作得很好,没有显示未定义的内容。

export const cryptoApi = createApi({
  reducerPath: "cryptoApi",
  baseQuery: fetchBaseQuery({ baseUrl }),
  endpoints: (builder) => ({
    getCryptos: builder.query({
      query: (name = 10) => createRequest(`/coins?limit=${name}`),
    }),
  }),
});

为什么我不能从另一个组件发送值

How do you pass query parameters to the api using Redux Toolkit RTK Query without getting it being undefined?

import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";

const cryptoApiHeaders = {
  "X-RapidAPI-Host": "...",
  "X-RapidAPI-Key": "...",
};

const baseUrl = "...";

const createRequest = (url) => ({ url, headers: cryptoApiHeaders });

export const cryptoApi = createApi({
  reducerPath: "cryptoApi",
  baseQuery: fetchBaseQuery({ baseUrl }),
  endpoints: (builder) => ({
    getCryptos: builder.query({
      query: (name) => createRequest(`/coins?limit=${name}`),
    }),
  }),
});

export const { useGetCryptosQuery } = cryptoApi;

When I pass the parameter down from the component, Its either It does not pass or it does not seem to recognize it, because it always shows undefined https://.../coins?limit=undefined. I really don't know what I'm doing wrong.

import React, { useState } from "react";
import millify from "millify";
import { Link } from "react-router-dom";
import { Card, Row, Col, Input } from "antd";

import { useGetCryptosQuery } from "../services/cryptoApi";

const Cryptocurrencies = () => {
  const count = 10;
  const { data: cryptosList, isFetching } = useGetCryptosQuery(count);
  const [cryptos, setCryptos] = useState(cryptosList?.data?.coins);

  return (
    <>
      <Row gutter={[32, 32]} className="crypto-card-container">
        {cryptos.map((currency) => (
          <Col xs={24} sm={12} lg={6} className="crypto-card" key={currency.id}>
            <Link to={`/crypto/${currency.uuid}`}>
              <Card
                extra={
                  <img
                    className="crypto-image"
                    src={currency.iconUrl}
                    alt={`${currency} currency`}
                  />
                }
                title={`${currency.rank}. ${currency.name}`}
                hoverable
              >
                <p>Price: {millify(currency.price)}</p>
                <p>Market Cap: {millify(currency.marketCap)}</p>
                <p>Daily Change: {millify(currency.change)}%</p>
              </Card>
            </Link>
          </Col>
        ))}
      </Row>
    </>
  );
};

export default Cryptocurrencies;

I tried hard coding it by putting value directly in the query and it worked perfectly without showing the undefined.

export const cryptoApi = createApi({
  reducerPath: "cryptoApi",
  baseQuery: fetchBaseQuery({ baseUrl }),
  endpoints: (builder) => ({
    getCryptos: builder.query({
      query: (name = 10) => createRequest(`/coins?limit=${name}`),
    }),
  }),
});

why can't I send the value from another component

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一个人的旅程 2025-01-24 17:44:20

问题是,您在第一次渲染时使用 undefined 初始化 cryptos 状态,并且 useState 调用在使用不同的 调用时永远不会更新代码>初始值。

只需删除那个无用的 useState 并离开

  const { data: cryptosList, isFetching } = useGetCryptosQuery(count);
  const cryptos = cryptosList?.data?.coins;

,一切都会正常工作。

PS:那是什么教程?我看过很多带有这种奇怪的(老实说毫无意义的)createRequest 函数的帖子。

The problem is that you are initializing your cryptos state with undefined on first render and that useState calls never update when they are called with a different initialValue.

Just remove that useless useState and leave

  const { data: cryptosList, isFetching } = useGetCryptosQuery(count);
  const cryptos = cryptosList?.data?.coins;

and everything will work fine.

PS: what tutorial is that? I have seen quite a bit of SO posts with that weird (and honestly quite pointless) createRequest function.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文