无法从异步获取 React 获取值

我做了一个 API fetch 来取回这些数据:


{

  "id": 1,

  "name": "Apple",

  "symbol": "AAPL",

  "lastPrice": {

    "id": 7,

    "currentPrice": 116.03,

    "openPrice": 115.55,

    "highPrice": 116.75,

    "lowPrice": 115.17,

    "previousClosePrice": 115.17,

    "timeOfRetrieval": "2020-11-26T19:04:35.150+00:00"

  }

}

这是我的反应代码:


function StockCard(props) {

  const [API, setAPI] = useState("http://localhost:8080/stock/getquote/AAPL")

  const [FetchInterval, setFetchInterval] = useState(300000)

  const [StockData, setStockData] = useState({})


  useEffect(() => {

    FetchData();



    const interval = setInterval(() => {

      FetchData();

    }, FetchInterval)


    return() => clearInterval(interval);


  }, [FetchInterval]);


  const FetchData = async () =>{

    console.log("FETCH CALLED");

    const resp = await Axios.get(API);

          setStockData(resp.data);

          

  }





    return(

        <div>

        <div className='card-container' style={{background: 'linear-gradient(to top, #141e30, #243b55)', padding: '4rem 1rem'}}>

        <CryptoCard

          currencyName={StockData.name}

          currencyPrice={StockData.lastPrice.currentPrice}

          icon={<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/4/46/Bitcoin.svg/2000px-Bitcoin.svg.png"/>}

          currencyShortName={StockData.symbol}

          trend='(8.54%) $563.47'

          trendDirection={1}

          chartData={[9200, 5720, 8100, 6734, 7054, 7832, 6421, 7383, 8697, 8850]}

        />

        </div>

        </div>

    )

}



export default StockCard;

它说无法在这一行读取未定义的属性“currentPrice”:currencyPrice={StockData.lastPrice.currentPrice}


如果我仅注销 StockData,那么我会获取值,但无法从原始 JSON 对象获取该内部对象


我究竟做错了什么?


胡说叔叔
浏览 108回答 2
2回答

一只萌萌小番薯

StockData最初是空对象,因此StockData.lastPrice将是未定义的。因此StockData.lastPrice.currentPrice就会出现错误。在获取字段之前,您应该检查是否StockData.lastPrice未定义currentPrice。<CryptoCard &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;currencyName={StockData.name} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;currencyPrice={StockData.lastPrice?&nbsp;StockData.lastPrice.currentPrice&nbsp;:&nbsp;0} />

叮当猫咪

首先是为什么它显示无法读取属性,因为每当react dom渲染它之前设置这个值,所以你只需要在这里添加快速检查,如果值存在则渲染否则使用一些默认值。用这个。function StockCard(props) {&nbsp; const [API, setAPI] = useState("http://localhost:8080/stock/getquote/AAPL")&nbsp; const [FetchInterval, setFetchInterval] = useState(300000)&nbsp; const [StockData, setStockData] = useState({})&nbsp; useEffect(() => {&nbsp; &nbsp; FetchData();&nbsp; &nbsp; const interval = setInterval(() => {&nbsp; &nbsp; &nbsp; FetchData();&nbsp; &nbsp; }, FetchInterval)&nbsp; &nbsp; return() => clearInterval(interval);&nbsp; }, [FetchInterval]);&nbsp; const FetchData = async () =>{&nbsp; &nbsp; console.log("FETCH CALLED");&nbsp; &nbsp; const resp = await Axios.get(API);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; setStockData(resp.data);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; }&nbsp; &nbsp;const { lastPrice: {currentPrice}, name, symbol } = StockData || {};&nbsp; &nbsp; return(&nbsp; &nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; <div className='card-container' style={{background: 'linear-gradient(to top, #141e30, #243b55)', padding: '4rem 1rem'}}>&nbsp; &nbsp; &nbsp; &nbsp; <CryptoCard&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; currencyName={name || ''}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; currencyPrice={currentPrice || 0}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; icon={<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/4/46/Bitcoin.svg/2000px-Bitcoin.svg.png"/>}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; currencyShortName={symbol || ''}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; trend='(8.54%) $563.47'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; trendDirection={1}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; chartData={[9200, 5720, 8100, 6734, 7054, 7832, 6421, 7383, 8697, 8850]}&nbsp; &nbsp; &nbsp; &nbsp; />&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; )}export default StockCard;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript