带有Context API警告的React Native:“允许进行请求周期,但可能会导致未初始化的值..." [英] React Native with Context API warnings: "Require cycles are allowed, but can result in uninitialized values... "

查看:62
本文介绍了带有Context API警告的React Native:“允许进行请求周期,但可能会导致未初始化的值..."的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在Expo React Native项目中使用React的Context API时,会收到以下警告:

When I use React's Context API in my Expo React Native project get this warning:

允许使用要求周期,但可能会导致未初始化的值.考虑重构以消除循环的需要.

Require cycles are allowed, but can result in uninitialized values. Consider refactoring to remove the need for a cycle.

我正在App.tsx中创建上下文:

Im creating a context in App.tsx:

import Start from "./start";

export const AppContext = React.createContext({
  isLandscape: true,
});

export default function App() {
  return (
    <AppContext.Provider value={{ isLandscape: false }}>
      <Start />
    </AppContext.Provider>
  );
}

在Start.tsx组件中,我使用上下文:

And in a Start.tsx component I'm using the context:

import { AppContext } from "./App"

export default function App() {
  const context = React.useContext(AppContext);
  console.log(context);

  return (
    <Text>Sutff</Text>
  );
}

我看起来像是警告,因为 App 导入了 Choose ,然后再次从 App 导入了上下文.需要允许循环,但可能会导致循环以未初始化的值.考虑重构以消除循环的需要

I looks like the warning is because App imports Choose which then imports the context from App again. Require cycles are allowed, but can result in uninitialized values. Consider refactoring to remove the need for a cycle

但是这不是应该使用Context API的方式吗?人们在React Native中使用Context API时通常如何处理?

However isn't this how the Context API is supposed to be used? How do people normally deal with this when using the Context API in React Native?

推荐答案

要中断一个循环,请将共享上下文移到单独的文件中.

To break a cycle, move the shared context to a separate file.

// in AppContext.js

export const AppContext = React.createContext({
  isLandscape: true,
});

,然后在 App.js Start.js 中,从该文件导入上下文.

and then in App.js and Start.js, import context from that file.

import { AppContext } from './AppContext'

因此,现在有了App-> AppContext和Start-> AppContext,而不是让App<-> Start相互依赖,从而打破了循环.

Thus, instead of having App <-> Start depend on each other, you now have App -> AppContext and Start -> AppContext, thus breaking the cycle.

这篇关于带有Context API警告的React Native:“允许进行请求周期,但可能会导致未初始化的值..."的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆