Redux Toolkit RTK 查询发送查询参数返回未定义

Redux Toolkit RTK Query sending query parameters is returning undefined

如何使用 Redux Toolkit RTK Query 将查询参数传递给 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;

我从组件往下传参数的时候,要么不传,要么好像不认识,因为一直显示undefinedhttps://.../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}`),
    }),
  }),
});

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

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

去掉那个没用的useState然后离开

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

一切都会正常进行。

PS: 这是什么教程?我已经看到很多 SO 帖子都有那个奇怪的(老实说毫无意义的)createRequest 函数。