【问题标题】:Why does useEffect break on page refresh?为什么 useEffect 在页面刷新时中断?
【发布时间】:2021-12-25 11:51:48
【问题描述】:

我目前正在尝试从 API 获取数据,以便在我的页面上使用它。我正在使用 React 进行编程,我正在尝试将 useEffect 与异步函数一起使用。

谁能告诉我为什么它在页面刷新时中断?

import React, { useEffect, useState } from 'react'
import axios from 'axios'
import './Cryptoinfo.css'

function Cryptoinfo() {
  const [coinprice, setCoinprice] = useState([])
  const url = `https://api.coingecko.com/api/v3/coins/markets?vs_currency=eur`

  useEffect(() => {
    async function fetchData() {
      try {
        const result = await axios.get(url)
        setCoinprice(result.data.slice(0, 10))
        console.log(result)
      } catch (e) {
        console.error(e)
      }
    }
    fetchData()
  }, [url])

  return (
    <>
      <div className='crypto-info-container'>
        <div className='name-pic'>
          <h3 className='crypto-info-img'>O</h3>
          <h3 className='crypto-info-name'>Name</h3> //this should be coinprice[0].name but it breaks if i do that.
        </div>
        <h3 className='crypto-info-price'>Price</h3>
        <h3 className='crypto-info-mc'>Marketcap</h3>
        <h3 className='crypto-info-vol'>Volume (24hr)</h3>
        <h3 className='crypto-info-sup'>Circulating supply</h3>
      </div>
    </>
  )
}

export default Cryptoinfo

【问题讨论】:

  • coinprice[0] 在获取您的数据之前不会有数据。所以你会做undefined.name 这会抛出一个错误
  • coinprice[0] 最初是未定义的,因为从 API 加载数据需要一秒钟。您可以通过在 JSX 中应用检查来处理此行为,例如:{ if(coinprice.length &gt; 0) return &lt;h1&gt;coinprice[0].id&lt;/h1&gt; }。它只是意味着当数据设置为状态时......渲染它

标签: reactjs use-effect


【解决方案1】:

该组件第一次渲染时,coinprice 的值为 []。 当您尝试从中获取 .name 时,它​​会中断,因为您无法从未定义的值中获取.name。

coinPrice[0] = 未定义

coinprice[0].name = 未捕获的类型错误

【讨论】:

    【解决方案2】:

    你可以尝试这样coinprice[0]?.name或者你必须在html开始之前设置条件{coinprice &amp;&amp; ( ---HTML--- )};希望它会帮助你。

    【讨论】:

    • 谢谢!我唯一缺少的是?在 coinprice[0] 后面。它现在正在工作!
    • 太好了,如果对您有帮助,请投票给我的答案。谢谢。
    【解决方案3】:

    有人提到问题是 coinpriceundefined 这是真的,所以这是一个三元解决方案,直到从 API 返回数据:

      return (
        <>
          <div className="crypto-info-container">
            {coinprice.length === 0 || coinprice.length === undefined ? (
              <h3 className="crypto-info-img">Loading</h3>
            ) : (
              <>
                <div className="name-pic">
                  <h3 className="crypto-info-img">O</h3>
                  <h3 className="crypto-info-name">Name</h3> //this should be coinprice[0]?.name but it
                  breaks if i do that.
                </div>
                <h3 className="crypto-info-price">Price</h3>
                <h3 className="crypto-info-mc">Marketcap</h3>
                <h3 className="crypto-info-vol">Volume (24hr)</h3>
                <h3 className="crypto-info-sup">Circulating supply</h3>
              </>
            )}
          </div>
        </>
      )
    

    更多关于 optional chaining 的信息,所以从技术上讲,它只是一个绕过 undefined 的选项。

    【讨论】:

      【解决方案4】:

      修改你的代码。

      import React, { useEffect, useState } from "react";
      import axios from "axios";
      
      function Cryptowatch() {
        const [data, setData] = useState([]);
        const url = `https://api.coingecko.com/api/v3/coins/markets?vs_currency=eur&per_page=5`;
      
        useEffect(() => {
          async function fetchData() {
            try {
              const result = await axios.get(url);
              setData(result.data);
              console.log(data);
            } catch (e) {
              console.error(e);
            }
          }
      
          fetchData();
        }, []);
        const cryptos = data.map((cryp) => {
          return (
            <div className="crypto-info-container">
              <div className="name-pic">
                <img src={data.image} className="crypto-info-img"></img>
                <h3 className="crypto-info-name">{cryp.name}</h3>
              </div>
              <h3 className="crypto-info-price">{cryp.current_price}</h3>
              <h3 className="crypto-info-mc">{cryp.market_cap}</h3>
              <h3 className="crypto-info-vol">{cryp.total_volume}</h3>
              <h3 className="crypto-info-sup">{cryp.total_supply}</h3>
            </div>
          );
        });
        return <>{data && cryptos}</>;
      }
      
      export default Cryptowatch;
      

      codesandbox link

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多