答案 0 :(得分:2)
如果我们应该访问多个屏幕或组件中的状态,那么我们必须使用来自 React 的 Context API 来实现全局状态。
查看文档了解更多详情:
https://reactjs.org/docs/context.html
如何使用上下文 API 实现全局状态的示例。
https://www.freecodecamp.org/news/react-context-in-5-minutes/
答案 1 :(得分:1)
您可以将要访问的值存储在公共父级上作为状态:
const [commonValue, setCommonValue] = useState("get me anywhere");
然后将状态和设置状态传递给孩子:
<Child1 value={commonValue} setCommonValue={setCommonValue} />
当您想更改该值并将更改反映到其他组件时,只需调用:
props.setCommonValue("I changed");
示例:https://codesandbox.io/s/strange-breeze-pheqo?file=/src/App.js:450-495