React-native useContext返回未定义

时间:2020-03-19 16:25:38

标签: reactjs react-native

我正在尝试学习反应并停留在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;

1 个答案:

答案 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示例。