useContext在Gatsby应用程序中返回空对象

问题描述

使用useContext()时,我得到一个空对象。

我创建了一个包含上下文,提供者和使用者的文件

src/utils/notesContext.js

import PropTypes from "prop-types"
import React,{ createContext,useState } from "react"

export const Context = createContext({})

export const Provider = props => {
  const {
    notes: initialNotes,selectedNote: initialSelectedNotes,children,} = props

  const [notes,setNotes] = useState([[""]])
  const [selectedNote,setSelectedNote] = useState([[""]])

  const addNewNote = note => {
    console.log(note)
  }

  const notesContext = {
    notes,setNotes,selectedNote,setSelectedNote,addNewNote,}

  return <Context.Provider value={notesContext}>{children}</Context.Provider>
}

export const { Consumer } = Context

Provider.propTypes = {
  notes: PropTypes.array,selectedNote: PropTypes.object,}

Provider.defaultProps = {
  notes: [],selectedNote: {},}

然后在我的索引文件中,我有以下内容

src/pages/index.js

import React,{ useContext } from "react"
import { Context } from "../utils/notesContext"

const Index = ({ data,location }) => {
  const initNote = data.note

  const notesContext = useContext(Context) // notesContext is empty
  const { notes,addNewNote } = notesContext
  addNewNote(initNote)
...
}

我是否使用上下文或提供者设置了不正确的内容?值得一提的另一件事是,它位于Gatsby应用程序中,因此不确定是否会导致我不知道的潜在问题。

谢谢!

解决方法

您的Index组件应在notesContext Provider内部使用。

详细了解Context.Provider

import { Context,Provider } from "./notesContext";

const Index = () => {
  const notesContext = useContext(Context);
  console.log(notesContext); // now this is not an empty object

  return <p>Index</p>;
};

export default function App() {
  // notice here,we're wrapping Index inside our Provider
  return (
    <Provider>
      <Index />
    </Provider>
  );
}

Edit sweet-goodall-pnsx0

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...