繁体   English   中英

一键取数据 object

[英]Fetch data in only one key object

我有一个对象数组存储在currentCoins state 中,如下所示:

const [currentCoins, setCurrentCoins] = useState([])
    
console.log(currentCoins)

[
    {
        "name": "algorand",
        "quantity": 1,
        "currentPrice": 0
    },
    {
        "name": "ethereum",
        "quantity": 9,
        "currentPrice": 0
    },
    {
        "quantity": 4,
        "name": "bitcoin",
        "currentPrice": 0
    }
]

我想在我的currentPrice中添加来自 API 的动态值,但我不知道如何 go 和组织它。

我曾想过这样的事情,但它不完整,我不知道如何将name传递给 API

useEffect(() => {
    setCurrentCoins(coinsCopy) // update currentCoins array from another array that can be updated by the user 

    const fetchPrices = async (name) => {
      await fetch(
        `https://api.coingecko.com/api/v3/coins/${name}`
      )
       // this endpoint returns the current price to res.market_data.current_price.usd

        .then((res) => res.json())
        .then((res) => {
          // processing here?
        });
    };
    fetchPrices();
  }, [coins])

处理应该添加到"// processing here?评论还是我走错了方向?

这样做的目标是覆盖我的每个对象的currentPrice"0"值。

useEffect(() => {
    setCurrentCoins(coinsCopy) // update currentCoins array from another array that can be updated by the user 
    fetchPrices();
  }, [coins])


    const fetchPrices = async () => {
      var copyArray = [...currentCoins];
      for(let c of copyArray ){
          var res = await fetch(
           `https://api.coingecko.com/api/v3/coins/${c.name}`
           )
          var data = await res.json()
          var currentPriceUSD = data.market_data.current_price.usd
          c.currentPrice =  currentPriceUSD 
      }
      setCurrentCoins(copyArray)

    };

暂无
暂无

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

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