有什么方法可以在上下文 API 中存储 API 数据吗?

Is there any method to store API data in context API?

我想获取 API 数据并将其存储在上下文 API 中并在其他组件中使用它。问题是,每当页面最初加载时,它都会给出

的错误
TypeError: Cannot read properties of undefined

这可能是因为 API 在之后获取数据,而组件在先渲染。 这是我的上下文代码:

 export const CrossRatesProvider = (props) => {
        const [crossRates, setCrossRates] = useState([])
    
        useEffect(() =>{
            async function fetchaud()
        { 
             await fetch('https://freecurrencyapi.net/api/v2/latest?apikey=6cfea260-497f-11ec-94b3-adf08d2418fe&base_currency=AUD')
        .then(res => res.json())
        .then(data => {
            setCrossRates(data);
            console.log(data)
        })
    }
        fetchaud();
         },[])
        const value = {
            crates: [crossRates, setCrossRates]
        }
    
        return (
            <CrossRatesContext.Provider value={value}>
            {props.children}
        </CrossRatesContext.Provider>
            
        )
    }

这是我使用上下文数据的组件:

export default function XnaToCountry() {
  const value = useContext(CrossRatesContext);
 const [cRates] = value.crates;
if ( !cRates.length) {
    return null;
  }
  return (
    <div>
       <Table responsive style={{fontSize:"small"}}>
      <tbody>
      <tr>
       <td>{(0.0119063760/cRates.data.AUD).toFixed(9)}</td>
      </tr>
      </tbody>
    </Table>
    </div>
  )
}

工作解决方案

上下文

import { useEffect, useState, createContext } from "react";

export const CrossRatesContext = createContext();

export const CrossRatesProvider = (props) => {
  const [crossRates, setCrossRates] = useState([]);

  useEffect(() => {
    async function fetchaud() {
      await fetch(
        "https://freecurrencyapi.net/api/v2/latest?apikey=6cfea260-497f-11ec-94b3-adf08d2418fe&base_currency=AUD"
      )
        .then((res) => res.json())
        .then((res) => {
          console.log(res.data);
          setCrossRates(res.data);
        });
    }
    fetchaud();
  }, []);
  const value = {
    crates: [crossRates, setCrossRates]
  };

  return (
    <CrossRatesContext.Provider value={value}>
      {props.children}
    </CrossRatesContext.Provider>
  );
};

index.js

import { CrossRatesProvider } from "./context";

const rootElement = document.getElementById("root");
ReactDOM.render(
    <CrossRatesProvider>
      <App />
    </CrossRatesProvider>,
  rootElement
);

用法

export default function App() {
  const value = useContext(CrossRatesContext);
  const [cRates] = value.crates;
  console.log(cRates);
  return <div></div>;
}

Codesandbox link - https://codesandbox.io/s/elegant-lumiere-emx5k?file=/src/App.js