如何在react.js 的功能组件的返回函数中访问useEffect 中存在的数组的值?

问题描述

我试图在 return 语句中访问 temp_arr 的符号、companyName、latestPrice、changePercent、marketCap。但它给出了错误TypeError:无法读取未定义的属性“companyName”。请帮我解决一下这个。这是我迄今为止尝试过的:

import { useEffect,useState } from "react";

让 temp_arr=[]; const Abc = props => {

const {companyName,symbol } = props;
const [appState,setAppState ] = useState({})
useEffect(() => {
    const API_token = `https://cloud.iexapis.com/stable/stock/${symbol}/quote?token=pk_042790e0f6f844c1a08763c9a03dc892`;
    fetch(API_token)
      .then(
        function(response){
            return response.json();
          }
      )
      .then(
        function(data){
            console.log("vdhsb",data);
            temp_arr.push({symbol:data['symbol'],companyName:data['companyName'],latestPrice:data['latestPrice'],changePercent:data['changePercent'],marketCap:data['marketCap']});
            setAppState(data)
            console.log("hjv kikg",temp_arr[0].changePercent);

        }
      )
      console.log("temp",temp_arr);
},[])


console.log("rutuja",props);
return (
    <>
        <p style={{color:"white"}}>{symbol}</p>
        <p style={{color:"white"}}>{temp_arr[0].companyName}</p>
    </>
);

}

导出认的ABC;

解决方法

像这样添加一些加载器或默认值:

const {companyName,symbol } = props;
const [appState,setAppState ] = useState({ companyName,symbol })
const [isLoading,setIsLoading ] = useState(false)
useEffect(() => {
    setIsLoading(true);
    const API_token = `https://cloud.iexapis.com/stable/stock/${symbol}/quote?token=pk_042790e0f6f844c1a08763c9a03dc892`;
    fetch(API_token)
      .then(
        function(response){
            return response.json();
          }
      )
      .then(
        function(data){
            setIsLoading(false)
            setAppState(data)

        }
      )
},[])


console.log("rutuja",props);
return (
    isLoading ? <ShowSomeLoader /> : <>
        <p style={{color:"white"}}>{appState.symbol}</p>
        <p style={{color:"white"}}>{appState.companyName}</p>
    </>
);