javascript - 如何使用我的 API 的 response.data 并将其格式化为 React.js 中的可用数组

标签 javascript reactjs

我正在使用 React 和 Pokemon API ( https://pokeapi.co/ ) 制作一个简单的网络应用程序,用户可以在其中按名称搜索 pokemon 并按类型过滤。

我成功实现了对自己数据的搜索。

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获取数据的方法,如下所示:

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() is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request. Setting state in this method will trigger a re-rendering.

更多信息在这里: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>

关于javascript - 如何使用我的 API 的 response.data 并将其格式化为 React.js 中的可用数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46663237/

相关文章:

javascript - 在预加载时如何使新窗口与加载指示器一起显示?

reactjs - React 和 TypeScript 中的表单,带有 DRY 更改句柄

javascript - React 功能组件 useEffect 钩子(Hook)在类组件生命周期中具有相等的依赖性

c# - 在登录表单页面上加载 javascript/css?

javascript - 为什么 JSON.stringify 返回未定义

javascript - Angular2 无法映射单个 JSON 对象?

javascript - 延迟启动力模拟

reactjs - 无法使用 npx create-react-app 创建新的 React 应用程序

javascript - 在同一个存储中可以有多个监听器中间件吗?

reactjs - npm install -g react-native-cli 与使用 npx react-native init <项目名称> 之间有什么区别?