簡體   English   中英

如何 map 和 API 與 Typescript 在 Z217C80CED5A5D142B0E105A86491709

[英]How to map an API with Typescript in ReactJS?

我是 Typescript 的新手,我必須從 API 獲取書籍清單。 我的教授給了我 javascript 中的代碼來執行此操作,但我必須在 typescript 中執行此操作並做出本機反應。

獲取 api:

import axios from 'axios';

const api = axios.create({
    baseURL: "https://hn.algolia.com/api/v1"
});

export default api;

列表組件:

import React, { Component } from "react";
import './List.css';

class List extends Component {
    constructor(props: any) {
        super(props);
        this.state = {};
    }

    render() {
        const apiData = this.props;

        return (
            <div className="List">
                {apiData?.map(item => (
                <div className="Livro">
                    <h3> {item.name}</h3>
                    <p> {item.authors.join(',')}</p>
                    <p><a href={item.url} target='_blank' rel="noreferrer"> {item.url}</a></p>
                </div>
                ))}
            </div>
        );
    }
}

export default List;

我將如何調用 List 組件的示例:

import React, {Component} from 'react';
import List from '../../components/list'
import api from '../../_config/api';
import './Welcome.css';

class Welcome extends Component {
  
  constructor(props){
    super(props);
    this.state = {sectionData:props.sectionData}
    this.filterList = this.filterList.bind(this);
    this.fetchData = this.fetchData.bind(this);
  }
  
  async fetchData(value) {

    const response = await api.get('/books?name='+value)

    this.setState({sectionData:response?.data})
    
  }

  async componentDidMount(){
    this.fetchData('');
  }

  render() { 
    const {sectionData} = this.state;


    return (
        <div className="Welcome">
             <List data={sectionData}/>
        </div>
      );
      
  }

}

export default Welcome;

僅適用於 Javascript 的代碼部分:

return (
            <div className="List">
                {apiData?.map(item => (  // error here
                <div className="Livro">
                    <h3> {item.name}</h3>
                    <p> {item.authors.join(',')}</p>
                    <p><a href={item.url} target='_blank' rel="noreferrer"> {item.url}</a></p>
                </div>
                ))}
            </div>
        );

我嘗試在 typescript 中以相同的方式執行此操作,但它返回此錯誤:

類型錯誤:類型'Readonly<{}> & Readonly<{ children?: ReactNode; 上不存在屬性'map' }>'。

有什么方法可以解決這個錯誤,或者不使用 map() 來解決 map 和 API 的其他方法嗎?

嘗試為您的List組件創建一個接口,並將該接口放在您的組件上,如下所示。

interface IListProps {
 apiData?: { name: string, authors: string[] }[];
}

interface IListState {}

class List extends Component<IListProps, IListState> {
// your code...
}

我還看到您在Welcome組件的render中的List組件上的props是錯誤的。

interface IWelcomeProps {
  sectionData?: { name: string, authors: string[] }[];
}

interface IWelcomeState extends IWelcomeProps {} // extends the props from IWelcomeProps

class Welcome extends Component<IWelcomeProps, IWelcomeState> {  
  // your code...

  render() {
    const { sectionData } = this.state; 
    return (
        <div className="Welcome">
             <List apiData={sectionData}/> // replace data by apiData
        </div>
      );
      
  }

}

您可以在此處找到有關如何使用接口的更多信息。

從 xZliman 的想法開始,我進行了研究並且在執行此操作時沒有出錯:

class List extends Component {
    constructor(props: any) {
        super(props);
        this.state = {};
    }

    render() {
        const apiData = this.props as {name: string, authors: string[], url: string}[]; // Here is the change

        return (
            <div className="List">
                {apiData.map(item => (
                <div className="Livro">
                    <h3> {item.name}</h3>
                    <p> {item.authors.join(',')}</p>
                    <p><a href={item.url} target='_blank' rel="noreferrer"> {item.url}</a></p>
                </div>
                ))}
            </div>
        );
    }
}

export default List;

也許這不是一個好的解決方案,但它可以作為一種解決方法完成工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM