简体   繁体   English

如何 map 和 API 与 Typescript 在 Z217C80CED5A5D142B0E105A86491709

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

I'm new to Typescript and I have to get a list of books from an API.我是 Typescript 的新手,我必须从 API 获取书籍清单。 My profesor gave me the code in javascript to do this, but I have to do this in typescript and react native.我的教授给了我 javascript 中的代码来执行此操作,但我必须在 typescript 中执行此操作并做出本机反应。

Getting api:获取 api:

import axios from 'axios';

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

export default api;

List component:列表组件:

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;

An example how I will call the List component:我将如何调用 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;

The part of the code that only works in Javascript:仅适用于 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>
        );

I tried to do this the same way in typescript, but it return this error:我尝试在 typescript 中以相同的方式执行此操作,但它返回此错误:

Type error: Property 'map' does not exist on type 'Readonly<{}> & Readonly<{ children?: ReactNode;类型错误:类型'Readonly<{}> & Readonly<{ children?: ReactNode; 上不存在属性'map' }>'. }>'。

Is there any way to resolve this error or another way to map an API without using map()?有什么方法可以解决这个错误,或者不使用 map() 来解决 map 和 API 的其他方法吗?

Try creating an interface for your List component, and put the interface on your component like below.尝试为您的List组件创建一个接口,并将该接口放在您的组件上,如下所示。

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

interface IListState {}

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

I also see that your props on the List component inside the render of the Welcome component are wrong.我还看到您在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>
      );
      
  }

}

You can find more info about how to use interfaces here .您可以在此处找到有关如何使用接口的更多信息。

Starting from xZliman idea, I researched and get no error when doind this:从 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;

Maybe it isn't a good solution, but it gets the work done as a workaround.也许这不是一个好的解决方案,但它可以作为一种解决方法完成工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM