以下是我的应用程序 struct 的伪代码示例.我正在try 与Reaction上下文全局共享状态,但在顶层更新状态会导致子组件重新呈现和重置状态(我认为)的问题.

// My top level where I store the state all other components need

function App() {
  const [userData, setUserData] = useState()

  const userContext = {
    userData,
    setUserData
  }

  return (
    <App>
      <Context.Provider value={userContext}>
        <Child />
        <Child />
        <Child />
      </Context.Context.Provider>
    </App>
  )
}



// My child component where I want to preserve state

const Child = () => {
  const [childState, setChildState] = useState('default value')

  // I want to keep this value
  setChildState('new value')

  // This is causing App.js to re-render, then Child to rerender, and I lose child state. Then on the next render my 'childState' is back to 'default value', when I want it to still be 'new value'
  const userContext = useContext(...)
  userContext.setUserData('some change to userdata')

  return {
    ...
  }
}

我的问题:

这是一个可以接受的应用程序 struct ,还是有问题?我可以做些什么来持久子组件网络中的状态,或者我需要以某种方式将共享状态移出App.js吗?

推荐答案

你错误地安排了useContext人的 struct .您可以在Reaction钩子中查看如何使用它.

其中一个功能齐全的示例可能会对您有所帮助:

const AppContext = React.createContext();

const AppProvider = ({ children }) => {
const [userData, setUserData]=useState('nothing here')

// any code you want to pass in the code
//e.g. a function
const randomFunction = ()=>{
//do something here
}

 return (
    <AppContext.Provider
      value={{
       userData,
       setUserData,
       randomFunction
      }}
    >
      {children}
    </AppContext.Provider>
  );
};

export const useGlobalContext = () => {
  return useContext(AppContext);
};

export { AppContext, AppProvider };

然后你所要做的就是包装所有你想要的组件(子组件),例如包装<App />,这样,或多或少所有的东西:

 <AppProvider>
      <App />
 </AppProvider>

现在,在这种情况下,您可以在所有代码中使用AppContext中的所有内容,如果需要,可以传递更多变量和函数,并通过使用以下命令来导入:

import { useGlobalContext } from '/pathYouHaveIt';

function App() {
  const {
       userData,
       setUserData,
       randomFunction,
  } = useGlobalContext();

// now you can use those like you have them set-up in the App()

Reactjs相关问答推荐

过滤对象数组并通过迭代对象数组将属性放入新数组

try 在Dockerfile中使用AWS CLI将React构建工件上传到S3时出错

在一个blog函数中调用setState钩子

值在返回页面时不更新,即使我已经更新了它们

将动态元素中的输入数据传输到Reaction

有没有办法在Shopify中显示自定义计算的交货日期?

Reaction Ploly:如何在多个子情节中共享zoom 状态

React:关于useEffect钩子如何工作的困惑

如何在物料界面react 的多选菜单中设置最大 Select 数限制

有没有办法在 React Router v6 中的路由匹配上运行一些逻辑/功能?

我可以在加载器函数中多次 fetch() 并使用一次 useloaderdata() 提取它吗?

从ReactDataGridtry 将数据传递给父组件

如何在 JS 中绘制具有不同笔画宽度的样条线

使用 react pro 侧边栏展开折叠菜单

React 测试库 - 如何断言异步函数之间的中间状态?

如何通过 React JS 中的映射将新元素添加到对象数据数组中

如何在 nextjs 中单击按钮时动态导入和渲染组件?

React Router 6.4CreateBrowserRouter子元素不显示

在 Reactjs 中状态发生变化时渲染一个新组件而不替换旧组件

如何实现两个 SVG 形状相互叠加的 XOR 操作?