[英]Unable to use React Context in deep descendant components
我正在嘗試使用React Context
和useReducer
鈎子在我的 React 應用程序中使用全局 state。 當我嘗試在遙遠的后代中使用我的useStateContext
掛鈎訪問 state 時,我返回未定義。 作為序言,我也在使用react-three-fiber
,我得到了我的上下文錯誤。
App.js
const App = () => {
return (
<GameProvider>
<AppState />
</GameProvider>
);
};
const AppState = () => {
const state = useStateContext() // this works. Direct child of Provider
return <Game />
}
const Game = () => {
const state = useStateContext(); // this works. 2nd descendant of Provider
return <Scene/>
};
const Scene = () => {
const state = useStateContext(); // this works. 3rd descendant
return (
<div id={styles.scene}>
<Canvas >
<OrbitControls minDistance={9} maxDistance={9} />
<ambientLight intensity={0.5} />
<spotLight position={[10, 15, 10]} angle={0.3} />
<Cube
size={5}
position={[0, 0, 0]}
/>
</Canvas>
</div>
);
};
const Cube = () => {
const state = useStateContext(); // returns undefined. What gives?
return <group></group>
}
StateContext.js
import React, { useContext, createContext, useReducer } from 'react'
import reducer from './reducer';
const StateContext = createContext();
const DispatchContext = createContext();
export const useDispatchContext = () => useContext(DispatchContext)
export const useStateContext = () => useContext(StateContext);
const initialState = {
test: 1
}
export const GameProvider = ({ children }) => {
const [state, dispatch] = useReducer(reducer, initialState)
return (
<DispatchContext.Provider value={dispatch}>
<StateContext.Provider
value={state}
>
{children}
</StateContext.Provider>
</DispatchContext.Provider>
)
}
我想使用上下文,因為我認為我可以在我的應用程序的任何后代中獲得 state。 我已經嘗試檢查有關此問題的反應文檔,但無濟於事。
編輯:
另外我認為重要的是要提到我正在使用react-three-fiber
,它將我的Cube
組件包裝在Canvas
中。
事實證明,這是使用帶有react-three-fiber
的 React Context api 的一個非常常見的問題。 通過文檔,我決定使用react-three-drei
的useContextBridge
,因為我已經在使用 package。 在這里找到我的解決方案的文檔
const ContextBridge = useContextBridge(StateContext, DispatchContext)
return (
<div id={styles.scene}>
<Canvas >
<OrbitControls minDistance={9} maxDistance={9} />
<ambientLight intensity={0.5} />
<spotLight position={[10, 15, 10]} angle={0.3} />
<spotLight position={[10, -15, -30]} angle={0.3} />
<ContextBridge>
<Cube
size={5}
position={[0, 0, 0]}
/>
</ContextBridge>
</Canvas>
</div>
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.