![](/img/trans.png)
[英]Ajax post always results in error, even though everything seems correct
[英]UseContext returns undefined even though everything seems proper
我有一個堆棧導航器,它打開一個屏幕,屏幕使用 Context 和提供程序,但useContext
似乎返回未定義。
我們有這個:
<Stack.Navigator>
<Stack.Screen name="preLogin" component={SomeScreen} />
<Stack.Screen name="postLogin" component={SomeScreen2} />
</Stack.Navigator>
在 SomeScreen2 我們有這個:
import React from 'react';
import {SampleContextProvider} from './provider/SampleContext';
import WelcomeScreen from './welcome';
const SomeScreen2Container = ({navigation}) => {
return (
<>
<SampleContextProvider>
<WelcomeScreen navigation={navigation}/>
</SampleContextProvider>
</>
);
};
export default SomeScreen2Container;
示例上下文:
import React from 'react';
const SampleContext = React.createContext({a:"a",b:"b"});
const SampleContextProvider = ({children}) => {
return (
<SampleContext.Provider>
{children}
</SampleContext.Provider>
);
};
export { SampleContext, SampleContextProvider };
在 WelcomeScreen 我正在使用useContext
:
import {SampleContext} from '../provider/SampleContext';
const ctx = useContext(SampleContext);
console.log("contextx=>", ctx);
它是未定義的。
隨時詢問更多信息
將您的SampleContext
文件更改為:
import React from 'react';
const SampleContext = React.createContext();
const SampleContextProvider = ({children}) => {
return (
<SampleContext.Provider value={{a: 'a', b: 'b'}}>
{children}
</SampleContext.Provider>
);
};
export {SampleContext, SampleContextProvider};
我在提供程序值道具中定義了您的默認上下文值,而不是作為createContext
的參數。
提供者的 value 屬性會覆蓋createContext
中設置的默認值。 這意味着如果您在使用提供程序時不設置value
,則默認值將覆蓋為未定義。
有關更多信息,請查看: React.createContext point of defaultValue? .
在您的歡迎屏幕中嘗試執行此操作
import {SampleContext} from '../provider/SampleContext';
const {a,b}= useContext(SampleContext);
console.log("contextx=> ", a+' '+b);
我認為解構該值可能會幫助您確認 sampleContext 是否具有上下文值!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.