开发者问题收集

为什么我得到未定义的结果?

2022-08-22
53

我想让“Screen”中的 setLoading 函数在“HomeScreen”中可用。所以

context.js

import { createContext } from "react";
export const LoadingContext = createContext();

screen.js 这是屏幕组件(HomeScreen 的父组件)。我想控制 HomeScreen(子组件)中 Modal 的状态。

import { Modal, StyleSheet, View } from "react-native";
import { useMemo, useState } from "react";
import { LoadingContext } from "../../context";

const Screen = ({ children}) => {
   const [loading, setLoading] = useState(false);

   const loadingContext = useMemo(() => {
      return { setLoading: setLoading };
   }, [loading]);

   return (
      <LoadingContext.Provider value={loadingContext}>
         <View>
            {children}
         </View>
      </LoadingContext.Provider>
   );
};

export default Screen;

HomeScreen.js

import { View, Text } from "react-native";
import { LoadingContext } from "../../context";
import { useContext} from "react";

const HomeScreen = ({ navigation }) => {

   const context = useContext(LoadingContext);

   console.log(context);  // undefined

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


export default HomeScreen;
1个回答

原因是您的 useContext 不在您的 Screen 组件内。请阅读 文档

The current context value is determined by the value prop of the nearest <MyContext.Provider> above the calling component in the tree.

您的 useContext 在父节点中查找上下文,但失败了,因此值未定义。

尝试在使用 HomeScreen 组件时将其与 Screen 组件捆绑,我假设它是您的路由器。

编辑: 这是您的修复

import { View, Text } from "react-native";
import { LoadingContext } from "../../context";
import { useContext} from "react";

const HomeScreen = ({ navigation }) => {

   const context = useContext(LoadingContext);

   console.log(context);  // undefined

   return <Text></Text>;
};

const WrappedHomeScreen = (props) => {
    return <Screen><HomeScreen {...props} /></Screen>;
}

export default WrappedHomeScreen;
TheWhiteFang
2022-08-22