【问题标题】:React ts Type 'Promise<X>' is missing the following properties from type 'X'React ts 类型“Promise<X>”缺少类型“X”的以下属性
【发布时间】:2021-04-02 01:09:33
【问题描述】:

我正在尝试将我的 API 请求移至单独的服务,但遇到了这个问题。

这是我的界面

export interface IProduct {
  id: any;
  productName: string;
  productDescription: string;
  productImage: string;
  productPrice: any;
  categoryId: string;
  category: any;
}

这是产品列表的组件

import React, {useEffect, useState} from 'react';

import {IProduct} from "../models"

interface IProps {
products: IProduct[];
}

export const ProductsList: React.FC<IProps> = ({products}) => {

  return (
    <div className="App">
      <ul className="posts">
        {products.map((products) => (
          <li key={products.id}>
            <h3>{products.productName}</h3>
            <p>{products.productDescription}</p>
            <h2>{products.productPrice}</h2>
          </li>
        ))}
      </ul>
    </div>
  );
}

export default ProductsList;

下一个 Api.tsx 我正在尝试提出请求:

import axios, { CancelTokenSource } from "axios";

import {IProduct} from "../models"
import React from 'react';

export const fetchAllProducts = async (setData: IProduct[]): Promise<IProduct[]> => {
  return axios.get<IProduct[]>("https://localhost:5001/api/ShowAllProducts")
    .then(response => {return setData = response.data });
}

最后是 APP.tsx

import axios, { CancelTokenSource } from "axios";
import {IProduct} from "./models"
import {ProductsList} from "./components/ProductsList";
import React from 'react';
import {fetchAllProducts} from './services/api';

const defaultProps:IProduct[] = [];


function App() {
  const [products, setProducts] = React.useState<IProduct[]> 
    (defaultProps)

  const [loading, setLoading]: [boolean, (loading: boolean) => void] = React.useState<boolean>(true);
  const [error, setError]: [string, (error: string) => void] = React.useState("");

  return (
    <div>
      <ProductsList products= {fetchAllProducts(products)}/>
    </div>
  );
}

export default App;

所以我在产品上的“=”符号之前返回 app.tsx 中的错误。

上面写着:

Type 'Promise<IProduct[]>' is missing the following properties from type 'IProduct[]': length, pop, push, concat, and 28 more.ts(2740)
ProductsList.tsx(6, 5): The expected type comes from property 'products' which is declared here on type 'IntrinsicAttributes & IProps & { children?: ReactNode; }'

【问题讨论】:

  • fetchAllProducts 返回 `Promise. You're trying to pass that as a prop, which expects an IProduct[]`。

标签: reactjs typescript axios


【解决方案1】:

在我看来,这条线

.then(response => {return setData = response.data });

应该改写为:

.then(response => Promise.resolve(response.data));

应该可以解决你的问题

【讨论】:

  • 谢谢,我想通了,我认为 const[X, Y] 中的第二个参数只是 var,但它是函数,所以我更改了我的 api 参数,以便它可以接受 func。
【解决方案2】:

错误消息中提到的那些属性是数组的属性。

interface IProps {
products: IProduct[];
}

export const ProductsList: React.FC<IProps> = ({products}) => {
...
}

在上面的代码中,您告诉 ProductsList 组件期望 array 命名产品作为道具。

但是在 APP.tsx 中一行

<ProductsList products= {fetchAllProducts(products)}/> 

您将 fetchAllProducts(products) 作为 products 道具发送。 fetchAllProducts(products) 是一个返回 promise 的函数,而不是一个 array

要修复它,您可以编写如下内容:

  function App() {
    const [products, setProducts] = React.useState<IProduct[]> 
      (defaultProps)  
    const [loading, setLoading]: [boolean, (loading: boolean) => void] = React.useState<boolean>(true);
    const [error, setError]: [string, (error: string) => void] = React.useState("");

    React.useEffect(async () => {
      const allproducts = await fetchAllProducts();
      setProducts(allproducts)
      }, [])
  
    return (
      <div>
        <ProductsList products={products}/>
      </div>
    );
  }

这样,当App 组件挂载时,您将获取所有产品并将array 作为products 属性传递给ProductsList

【讨论】:

  • 谢谢,我想通了,我认为 const[X, Y] 中的第二个参数只是 var,但它是函数,所以我更改了我的 api 参数,以便它可以接受 func。
【解决方案3】:

谢谢大家,我想通了,顺便说一句,你的回答让我明白了一件事。我是这么想的

const [products, setProducts] = React.useState<IProduct[]>(defaultProps) 

就像 typesriptish {set;得到;} 从 .net 大声笑。 但现在我知道第二个参数是函数。所以我只是在我的 api.tsx 文件中更改了参数,所以它现在接受函数。

所以组件和界面保持不变

这是我的 api.tsx

export const fetchAllProducts = async (func: any): Promise<IProduct[]> => {
return axios.get<IProduct[]> ("https://localhost:5001/api/ShowAllProducts")
.then(response => {return func(response.data)});}

这里是 APP.tsx

const defaultProps:IProduct[] = [];

function App() {
const [products, setProducts] = React.useState<IProduct[]>(defaultProps) 
const [loading, setLoading]: [boolean, (loading: boolean) => void] = 
React.useState<boolean>(true);
const [error, setError]: [string, (error: string) => void] = 
React.useState("");

React.useEffect(() => {
async () => await fetchAllProducts(setProducts);
}, [])

 return (
<div>
  <ProductsList products={products}/>
</div>
);
}
export default App;

【讨论】:

    猜你喜欢
    • 2019-06-21
    • 2022-11-21
    • 2019-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-22
    • 1970-01-01
    • 2020-09-12
    相关资源
    最近更新 更多