React useContext() 总是在不同的子进程中返回初始值

发布于 2025-01-19 10:07:32 字数 2599 浏览 0 评论 0原文

我需要通过多个组件共享全局变量,看来我的上下文无法正常工作。

我在一个分开的文件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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

暮年慕年 2025-01-26 10:07:32

托盘状态和反应上下文值正常更新。问题在于,您正在使用RAW Anchor标签(&lt; a/&gt;)在页面之间导航,这正在重新加载整个页面/应用程序。换句话说,该应用程序重新启动并重置了反应状态。

使用链接组件发布声明性导航操作以围绕应用程序移动。

而不是这样:

<a href="/other">Move to Other</a>

导入并使用link component:

import { Link } from "react-router-dom";

...

<Link to="/other">Move to Other</Link>

”编辑react-usecontext-always-returning-initial-initial-intial-in-in-different-children”

“在此处输入映像说明”

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:

<a href="/other">Move to Other</a>

Import and use the Link component:

import { Link } from "react-router-dom";

...

<Link to="/other">Move to Other</Link>

Edit react-usecontext-always-returning-initial-value-in-different-children

enter image description here
enter image description here
enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文