React useContext() 总是在不同的子进程中返回初始值
我需要通过多个组件共享全局变量,看来我的上下文无法正常工作。
我在一个分开的文件globalContext.tsx
中声明:
export type GlobalContent = {
entities: entity[]
setEntities:(c: entity[]) => void,
pallets: string[],
setPallets:(c: string[]) => void,
}
export const GlobalContext = createContext<GlobalContent>({
entities: [], // set a default value
setEntities: () => {},
pallets: [],
setPallets: () => {}
})
然后,在App.tsx中初始化和我的值,然后将所有树包装在提供商中:
function App() {
// Init global variables, accessible everywhere using useContext hook
const [entities, setEntities] = useState<entity[]>([])
const [pallets, setPallets] = useState<string[]>(["hello"])
let defaultGlobals: GlobalContent = { entities, setEntities, pallets, setPallets }
return (
<GlobalContext.Provider value={defaultGlobals}>
<BrowserRouter>
<Routes>
<Route path="/" element={<Home/>}/>
<Route path="/picking" element={<Picking/>}/>
<Route path="/control" element={<Control/>}/>
<Route path="/place" element={<Place/>}/>
<Route path="*" element={<NotFound/>}/>
</Routes>
</BrowserRouter>
</GlobalContext.Provider>
)
}
因此,应该有。在我的组件中(例如,假设&lt; choting/&gt;),我可以通过使用以下内容来找到我的默认值:
const { entities, setEntities, pallets, setPallets } = useContext(GlobalContext)
但是当我在另一个组件(&lt; control/&gt; or&&&&&&&&&&les&&&&lt; &gt;)使用:
const { entities, setEntities, pallets, setPallets } = useContext(GlobalContext)
我不断获得默认值(又称“ defaultglobals”,带有[“ hello”]数组)。
我尝试使用相应的设置更改我的实体
或palles
内容,并且从USECONTEXT提取的变量从一个组件到另一个组件都独立。 一开始仍然获得默认值。
似乎有些事情正在打破上下文,或者我在这里做错了什么。 有帮助吗?
这是指向运行 codesandbox )的链接。
示例消费者:
export default function Home() {
const { entities, setEntities, pallets, setPallets } = useContext(
GlobalContext
);
return (
<div>
<a href="/other">Move to Other</a>
<h1>Home component</h1>
<button onClick={() => setPallets([...pallets, "newPallet"])}>
Add pallet
</button>
{pallets.map((pallet) => {
return <p>{pallet}</p>;
})}
</div>
);
}
I need to share global variables through multiple components, and it seems that my context is not working as expected.
I declared in a seperated file globalContext.tsx
:
export type GlobalContent = {
entities: entity[]
setEntities:(c: entity[]) => void,
pallets: string[],
setPallets:(c: string[]) => void,
}
export const GlobalContext = createContext<GlobalContent>({
entities: [], // set a default value
setEntities: () => {},
pallets: [],
setPallets: () => {}
})
Then, initialize and my values in my App.tsx, then wrapping all my tree in the Provider :
function App() {
// Init global variables, accessible everywhere using useContext hook
const [entities, setEntities] = useState<entity[]>([])
const [pallets, setPallets] = useState<string[]>(["hello"])
let defaultGlobals: GlobalContent = { entities, setEntities, pallets, setPallets }
return (
<GlobalContext.Provider value={defaultGlobals}>
<BrowserRouter>
<Routes>
<Route path="/" element={<Home/>}/>
<Route path="/picking" element={<Picking/>}/>
<Route path="/control" element={<Control/>}/>
<Route path="/place" element={<Place/>}/>
<Route path="*" element={<NotFound/>}/>
</Routes>
</BrowserRouter>
</GlobalContext.Provider>
)
}
So, there should be it. Within my components (let's say <Picking/> for example), I can get find back my default values by using the following :
const { entities, setEntities, pallets, setPallets } = useContext(GlobalContext)
But when I grab this data in another component (<Control/> or <Place/>) using :
const { entities, setEntities, pallets, setPallets } = useContext(GlobalContext)
I keep getting the default value (a.k.a. the "defaultGlobals", with ["hello"] array).
I tried changing my entities
or pallets
content using the corresponding setters, and the variables extracted from the useContext are definitively independant from a component to another.
Still getting default values at first.
Seems something is breaking the context or I am doing something wrong here.
Any help ?
Here's a link to a running codesandbox.
Example consumer:
export default function Home() {
const { entities, setEntities, pallets, setPallets } = useContext(
GlobalContext
);
return (
<div>
<a href="/other">Move to Other</a>
<h1>Home component</h1>
<button onClick={() => setPallets([...pallets, "newPallet"])}>
Add pallet
</button>
{pallets.map((pallet) => {
return <p>{pallet}</p>;
})}
</div>
);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
托盘
状态和反应上下文值正常更新。问题在于,您正在使用RAW Anchor标签(&lt; a/&gt;
)在页面之间导航,这正在重新加载整个页面/应用程序。换句话说,该应用程序重新启动并重置了反应状态。使用
链接
组件发布声明性导航操作以围绕应用程序移动。而不是这样:
导入并使用
link
component:The
pallets
state and React context value are updating just fine. The issue is that you are using raw anchor tags (<a />
) to navigate between pages and this is reloading the entire page/app. In other words, the app is remounted and React state is reset.Use the
Link
component to issue declarative navigation actions to move around the app.Instead of this:
Import and use the
Link
component: