gpt4 book ai didi

javascript - TypeError : this. state.rates.map 不是函数 - Reactjs

转载 作者:行者123 更新时间:2023-12-02 22:11:10 25 4
gpt4 key购买 nike

我在尝试映射 API 响应后收到此错误。感谢你的帮助。我可以在控制台中看到响应,但

  • 未呈现。由于这个原因,我已经成功解决了打字错误:ReactJs - TypeError: Cannot read property 'map' of undefined但仍在努力前进。

    谢谢。

    代码如下:

    import React from 'react';
    import './App.css';
    import prettyFormat from 'pretty-format';
    import axios from 'axios';

    class App extends React.Component {

    state = {
    rates: []
    }
    onSubmitExchange = this.onSubmitExchange.bind(this);


    onSubmitExchange() {
    axios({
    "method":"GET",
    "url":"https://coingecko.p.rapidapi.com/exchange_rates",
    "headers":{
    "content-type":"application/octet-stream",
    "x-rapidapi-host":"coingecko.p.rapidapi.com",
    "x-rapidapi-key":"f4756b8409msh762478a357cd070p10685fjsnce9080fa5478"
    }
    })
    .then((response)=>{
    //console.log(response)
    //response is an object with a data property that contains the rates
    const { rates } = response.data;
    this.setState({ rates })
    })

    }

    render() {
    let xrpName = (this.state.rates.xrp && this.state.rates.xrp) ? this.state.rates.xrp.name : undefined
    console.log(xrpName)
    console.log(this.state.rates)

    const items = this.state.rates.map((item) => {return <li>{ item.name }</li> });


    return (
    <div>
    <ul>
    { items }
    </ul>
    <button onClick={this.onSubmitExchange}>FIRE</button>
    </div>
    )

    }
    }

    export default App;
  • 最佳答案

    API 返回一个对象。你不能像数组一样映射它。第一个改变

    state = {
    rates: []
    }

    state = {
    rates: {}
    }

    然后使用Object.keys(rates)来映射它。

    关于javascript - TypeError : this. state.rates.map 不是函数 - Reactjs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59556452/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com