简体   繁体   English

在 react.js 的一个组件中映射来自不同 API 的数据?

[英]Mapping data from different API in one component in react.js?

I'm working on a challenge.我正在接受挑战。 My task is to use two APIS: https://api.thecatapi.com/v1/images/search?breed_id=abys and https://api.thecatapi.com/v1/breeds我的任务是使用两个 APIS: https ://api.thecatapi.com/v1/images/search ? breed_id = abys 和https://api.thecatapi.com/v1/breeds

to display image and description.显示图像和描述。 So far I've got:到目前为止,我有:

 import React, { Component } from 'react' import ReactDOM from 'react-dom' import axios from 'axios' const Cat = ({ cat: { name, weight, life_span, description } }, { image: url }) => { return ( <div className='cat'> <div className='cat_wrapper'> <img src={url} alt="catimage" /> </div> <h3 className='cat_breed'>{name.toUpperCase()}</h3> <div className='country_text'> <span>Weight:{weight.metric}</span> <span>Lifespan: {life_span}</span> <div>Description: {description}</div> </div> </div> ) } class App extends Component { state = { data: [], data2: [] } componentDidMount() { this.fetchCatData() } fetchCatData = async () => { const url = 'https://api.thecatapi.com/v1/breeds' const images = 'https://api.thecatapi.com/v1/images/search?breed_id=abys' try { const response = await axios.get(url) const response2 = await axios.get(images) const data = await response.data const data2 = await response2.data2 this.setState({ data, data2 }) } catch (error) { console.log(error) } } render() { return ( <div className='App'> <div> <p>There are {this.state.data.length} cats in the api</p> <div className='wrapper'> {this.state.data.map((cat, image) => ( <Cat image={this.state.data2.image} cat={cat} key={cat.id} /> ))} </div> </div> </div> ) } } const rootElement = document.getElementById('root') ReactDOM.render(<App />, rootElement)

But it returns an error但它返回一个错误

× TypeError: Cannot read property 'image' of undefined × 类型错误:无法读取未定义的属性“图像”

How to fix it?如何解决?

-=EDITED=- -=编辑=-

so, now it reads the 'url' key, earlier it was undefined .所以,现在它读取'url'键,之前它是undefined I managed to display a hardcoded image of a cat, now I wonder how to map all the different images to its proper contents.我设法显示了一张猫的硬编码图像,现在我想知道如何将所有不同的图像映射到其正确的内容。

 import React, { Component } from 'react' import ReactDOM from 'react-dom' import axios from 'axios' const Cat = ({ cat: { name, weight, life_span, description, url }}) => { return ( <div className='cat'> <div className='cat_wrapper'> <img alt="catimage" src={url} width="50" height="30"/> </div> <h3 className='cat_breed'>{name.toUpperCase()}</h3> <div className='country_text'> <span>Weight:{weight.metric}</span> <span>Lifespan: {life_span}</span> <div>Description: {description}</div> </div> </div> ) } class App extends Component { state = { data: [], data2: [] } componentDidMount() { this.fetchCatData() } fetchCatData = async () => { const url = 'https://api.thecatapi.com/v1/breeds' const images = 'https://api.thecatapi.com/v1/images/search?breed_id=abys' try { const response = await axios.get(url) const response2 = await axios.get(images) const data = await response.data const data2 = await response2.data this.setState({ data, data2 }) } catch (error) { console.log(error) } } render() { return ( <div className='App'> <div> <p>There are {this.state.data.length} cats in the api</p> <div className='wrapper'> {this.state.data.map((cat) => { cat.url = this.state.data2[0].url; return <Cat cat={cat} key={cat.id}/> } )} </div> </div> </div> ) } } const rootElement = document.getElementById('root') ReactDOM.render(<App />, rootElement)

you better first fetch all data cats then, for each cat make a request to fetch its correspondent image for that cat and add an image or url attribute like:您最好先获取所有数据猫,然后为每只猫发出请求以获取该猫的对应图像并添加图像或 url 属性,例如:

  fetchCatData = async () => {
    const catsDataUrl = 'https://api.thecatapi.com/v1/breeds'
    const searchImgUrl = 'https://api.thecatapi.com/v1/images/search?breed_id='
    try {
      const catsResponse = await axios.get(catsDataUrl)
      const cats = catsResponse.data
      
      await Promise.allSettled(cats.map(async (cat) => {
        const response = await axios.get(`${searchImgUrl}${cat.id}`)
        cat.url = response.data[0].url // data is an array with a single object        
      }))

      this.setState({cats}) // I changed state name for cats to be more semantic
      
    } catch (error) {
      console.log(error)
    }
  }

now you don't need data2, you already have url.现在你不需要data2,你已经有了url。 fwiw, your error is given the fact that data2 is an array and not an object with image attribute. fwiw,你的错误是因为 data2 是一个数组而不是一个具有image属性的对象。

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

相关问题 如何将state.data.length从一个组件发送到React.js中的另一个组件 - How to send state.data.length from one component to different component in React.js 如何在 React.js 中将状态/数据从一个组件传递到另一个组件(特别是 riot api) - How to pass state/data from one component to another in React.js (riot api specifically) 如何在 React.JS 中将数据从一个组件传递到另一个组件 - How to pass data from one component to another in React.JS 在 React.js 的一个组件中从 2 个 URL 获取数据 - Get data from 2 URLs in one component in React.js 如何从react.js中不同组件中的一个组件访问方法? - How do access methods from one component in a different component in react.js? 当我按下按钮时如何将数据从一个组件发送到另一个组件。 React.js - how to send the data from one component to another component when i press a button. React.js 我如何将数据从一个组件传递到 react.js 中的另一个组件 - how can i pass data from one component into another component in react.js React.js - 使用不同设置多次使用一个组件 - React.js - Using one component multiple times with different settings React.js为具有不同数据的同一组件生成动态路由 - React.js generate dynamic routes for the same component with different data 在 React.js 中获取 API 获取的数据后加载组件 - Load a component after getting API fetched data in React.js
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM