我正在使用 TypeScript 开发 Next.js 应用程序,但出现此错误:
“TypeError:无法解构'(0,react__WEBPACK_IMPORTED_MODULE_0__.useContext)(...)'的属性'主题',因为它为空。”
这是我的 _app.tsx 文件:
import { useContext } from "react"
import { ThemeProvider } from "styled-components"
import ContextProvider from "../context/Context"
import { Context } from "../context/Context"
import GlobalStyle from "../styles/global"
export default function App({ Component, pageProps }) {
const { theme } = useContext(Context)
return (
<ContextProvider>
<ThemeProvider theme={theme}>
<GlobalStyle />
<Component {...pageProps} />
</ThemeProvider>
</ContextProvider>
)
}
这是我的 Context.tsx 文件:
import { createContext, useState } from "react"
import Light from "../styles/themes/Light"
import Dark from "../styles/themes/Dark"
interface Props {
theme: any;
setTheme: any;
handleTheme(): void;
}
export const Context = createContext<Props>(null)
export default function ContextProvider({ children }) {
const [theme, setTheme] = useState(Dark)
function handleTheme() {
setTheme(theme.title === "Dark" ? Light : Dark)
}
return(
<Context.Provider
value={{
theme,
setTheme,
handleTheme
}}
>
{children}
</Context.Provider>
)
}
我一直收到此错误,但我不知道如何解决它。
有人可以帮助我吗?
在 ContextProvider 组件中使用“createContext”的行需要有一个基于接口“Props”的初始对象,并且不为 null。
在 Nextjs 13 中,您需要将“use client”指令放在组件顶部。
我遇到了类似的错误,地图不是主题:
TypeError:无法解构“(0,react_
”的属性“map”
我有这段代码并单击弹出窗口导致了错误:
<Map
initialViewState={INITIAL_VIEW_STATE}
style={{ width: '100%', height: '100%' }}
mapStyle={mapStyle}
mapboxAccessToken={accessToken}
onMouseMove={handleMouseMove}>
<DeckGLOverlay ref={deckRef} />
<NavigationControl position="top-left" />
</Map>
{selected && (
<Popup
longitude={selected.LongitudeDeg}
latitude={selected.LatitudeDeg}
closeButton={true}
closeOnClick={false}
onClose={() => setSelected(null)}
anchor="bottom"
>
<div>
<p>Operation Number: {selected.OperationNumber}</p>
<p>Altitude: {selected.AltitudeFtAMSL} ft AMSL</p>
<p>Speed: {selected.Speed} knots</p>
</div>
</Popup>
)}
将弹出窗口包裹在地图中解决了这个问题:
<Map
initialViewState={INITIAL_VIEW_STATE}
style={{ width: '100%', height: '100%' }}
mapStyle={mapStyle}
mapboxAccessToken={accessToken}
onMouseMove={handleMouseMove}>
<DeckGLOverlay ref={deckRef} />
<NavigationControl position="top-left" />
{selected && (
<Popup
longitude={selected.LongitudeDeg}
latitude={selected.LatitudeDeg}
closeButton={true}
closeOnClick={false}
onClose={() => setSelected(null)}
anchor="bottom"
>
<div>
<p>Operation Number: {selected.OperationNumber}</p>
<p>Altitude: {selected.AltitudeFtAMSL} ft AMSL</p>
<p>Speed: {selected.Speed} knots</p>
</div>
</Popup>
)}
</Map>