我正在尝试学习反应并停留在useContext上。我尝试导出Provider并也更改了provider的值数据,但仍返回undefined! 我的情境
import React from 'react';
const BlogContext = React.createContext();
export const BlogProvider = ({ children }) => {
const blogPosts = [
{ title: "Blog Post #1" },
{ title: "Blog Post #2" }
];
return (
<BlogContext.Provider value={blogPosts}>
{children}
</BlogContext.Provider>
);
};
export default BlogContext;
我的屏幕
import React, { useContext } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { BlogContext } from '../context/BlogContext';
const IndexScreen = () => {
const blogPosts = useContext(BlogContext);
console.log(blogPosts);
return (
<View>
<Text>Index Screen</Text>
</View>
);
};
const styles = StyleSheet.create({
});
export default IndexScreen;
答案 0 :(得分:0)
export const ...
时,请用大括号{ }
导入export default ...
,则应导入不加大括号。所以您混合了它:
// just export the context
export const BlogContext = createContext()
const BlogProvider = ({ children }) => {
const blogPosts = [...]
return (
<BlogContext.Provider value={blogPosts}>
{children}
</BlogContext.Provider>
)
}
// export default the component
export default BlogProvider
第二,您需要使用BlogProvider
组件将应用包装:
// App.js
import React from "react"
import BlogProvider from "./context/AppContext"
import IndexScreen from "./screens/IndexScreen"
const App = () => {
return (
<BlogProvider>
<IndexScreen />
// More screens...
</BlogProvider>
)
}
export default App
这是一个有效的codeSandbox示例。