为什么我得到未定义的道具?

Why am I getting undefined prop?

下面是我在 React 中的 Header 组件:

import React from 'react'
import {AppBar} from '@material-ui/core'
import {Typography,Container,Toolbar,Select,MenuItem} from '@material-ui/core'
import {useNavigate} from 'react-router-dom'
import { CryptoState } from './CryptoContext'
const Header = () => {
 const navigate=useNavigate();
 const {currency,setCurrency}=CryptoState();
  return (
       <AppBar>
           <Container>
               <Toolbar>
                   <Typography onClick={()=>navigate('/')}>
                       CryptoTracker
                   </Typography>
                   <Select value={currency}
                   onClick={(e)=>setCurrency(e.target.value)}
                   >
                       <MenuItem value="USD">USD</MenuItem>
                       <MenuItem value="INR">INR</MenuItem>
                   </Select>
               </Toolbar>
           </Container>
       </AppBar>
  )
}

export default Header

我已将 ContextAPI 用于高效状态 Management.CryptoState 用于此 purpose.I 已将状态导入 Header 并使用对象解构获取必要的道具。

下面是我的上下文文件:

import React from 'react'
import { useEffect } from 'react';
import { createContext ,useState,useContext } from 'react';
const CryptoContext = ({children}) => {
    const Crypto=createContext();
    const [currency,setCurrency]=useState("USD");
    const [symbol,setSymbol]=useState("$");

    useEffect(()=>{
      if(currency=="INR")
      setSymbol("₹") 
      else
      setSymbol("$") 
    })
  return (
    <Crypto.Provider value={{currency,symbol,setCurrency}}>
        {children}
    </Crypto.Provider>
  )
}

export default CryptoContext;
export const CryptoState=()=>{
    return useContext(Crypto);
}

我在 Header 组件中收到此错误:Header.js:8 Uncaught TypeError: Cannot destructure property 'currency' of '(0 , _CryptoContext__WEBPACK_IMPORTED_MODULE_1__.CryptoState)(...)' as it is undefined.

在您的 CryptoState 函数中,Crypto 未定义,因为它已在 CryptoContext 中初始化。

Crypto 上下文应从您的 CryptoContext 组件中提取,并在任何函数之外声明为 const 可用