簡體   English   中英

如何使用我的API的response.data並將其格式化為React.js中的可用數組

[英]How to use my API's response.data and format it into a usable array in React.js

我正在使用React和Pokemon API( https://pokeapi.co/ )制作一個簡單的Web應用程序,用戶可以按名稱搜索小寵物並按類型過濾。

我成功地實現了搜索我自己的數據。

constructor() {
    super();
    this.state = {

        contactData: [
            { name: 'Abet', phone: '010-0000-0001' },
            { name: 'Betty', phone: '010-0000-0002' },
            { name: 'Charlie', phone: '010-0000-0003' },
            { name: 'David', phone: '010-0000-0004' }
        ]

    };
}

使用我擁有的contactData,我成功搜索包含關鍵字的數據。

 render() {

        const mapToComponents = (data) => {
            //data.sort();

            data = data.filter(
                (contact) => {
                    return contact.name.toLowerCase()
                    .indexOf(this.state.keyword.toLowerCase()) > -1;
                }
                )

          return data.map((contact, i) => {
            return (<ContactInfo contact={contact} key={i}/>);
          });
        };

        return(


            <div className="Home">

                <input
                name = "keyword"
                placeholder = "Search"
                value = { this.state.keyword }
                onChange = { this.handleChange }
                />
                <div className="info">{ mapToComponents(this.state.contactData)}</div>

            </div>
        )
    }

我的問題是,我不知道如何使用Pokemon API的響應數據做同樣的事情。 我的響應數據在控制台中如下所示:

{count: 811, previous: null, results: Array(20), next: "https://pokeapi.co/api/v2/pokemon/?offset=20"}
count
:
811
next
:
"https://pokeapi.co/api/v2/pokemon/?offset=20"
previous
:
null
results
:
Array(20)
0
:
{url: "https://pokeapi.co/api/v2/pokemon/1/", name: "bulbasaur"}
1
:
{url: "https://pokeapi.co/api/v2/pokemon/2/", name: "ivysaur"}
2
:
{url: "https://pokeapi.co/api/v2/pokemon/3/", name: "venusaur"}
3
:
{url: "https://pokeapi.co/api/v2/pokemon/4/", name: "charmander"}
4
:
{url: "https://pokeapi.co/api/v2/pokemon/5/", name: "charmeleon"}
5
:
{url: "https://pokeapi.co/api/v2/pokemon/6/", name: "charizard"}
6
:
{url: "https://pokeapi.co/api/v2/pokemon/7/", name: "squirtle"}
7
:
{url: "https://pokeapi.co/api/v2/pokemon/8/", name: "wartortle"}
8
:
{url: "https://pokeapi.co/api/v2/pokemon/9/", name: "blastoise"}
9
:
{url: "https://pokeapi.co/api/v2/pokemon/10/", name: "caterpie"}
10
:
{url: "https://pokeapi.co/api/v2/pokemon/11/", name: "metapod"}
11
:
{url: "https://pokeapi.co/api/v2/pokemon/12/", name: "butterfree"}
12
:
{url: "https://pokeapi.co/api/v2/pokemon/13/", name: "weedle"}
13
:
{url: "https://pokeapi.co/api/v2/pokemon/14/", name: "kakuna"}
14
:
{url: "https://pokeapi.co/api/v2/pokemon/15/", name: "beedrill"}
15
:
{url: "https://pokeapi.co/api/v2/pokemon/16/", name: "pidgey"}
16
:
{url: "https://pokeapi.co/api/v2/pokemon/17/", name: "pidgeotto"}
17
:
{url: "https://pokeapi.co/api/v2/pokemon/18/", name: "pidgeot"}
18
:
{url: "https://pokeapi.co/api/v2/pokemon/19/", name: "rattata"}
19
:
{url: "https://pokeapi.co/api/v2/pokemon/20/", name: "raticate"}
length
:
20
__proto__
:
Array(0)
__proto__
:
Object

如何格式化我就像我創建的contactData並顯示它進行搜索?

首先,您需要一種方法從API fetch數據,如下所示:

loadData() {
  fetch('https://pokeapi.co/api/v2/pokemon/')
    .then(result => result.json())
    .then(items => this.setState({ data: items })
}

然后創建另一個方法componentDidMount並傳遞loadData()

componentDidMount() {
  this.loadData()
}

從官方React文檔:

在裝入組件后立即調用componentDidMount() 需要DOM節點的初始化應該放在這里。 如果需要從遠程端點加載數據,這是實例化網絡請求的好地方。 在此方法中設置狀態將觸發重新渲染。

更多信息: React Components

JSFiddle示例:

 class Data extends React.Component { constructor(props) { super(props); this.state = { data: [] }; } componentDidMount() { this.loadData() } // Fetch data from API: loadData() { fetch(`https://pokeapi.co/api/v2/pokemon/`) .then(result => result.json()) .then(items => this.setState({data: items})) } render() { const mapToComponents = data => { // Your logic... // Here you can use data... }; return ( <div> <h1>Pokemon's:</h1> <ul> {this.state.data.results !== undefined ? this.state.data.results.map((x, i) => <li key={i}>{x.name}</li>) : <li>Loading...</li> } </ul> <h1>THIS.STATE.DATA:</h1> <pre> {JSON.stringify(this.state.data, null, 2)} </pre> </div> ); } } ReactDOM.render( <Data />, document.getElementById('container') ); 
 <div id="container"> <!-- This element's contents will be replaced with your component. --> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 

暫無
暫無

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

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