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

时间:2020-08-10 23:43:55

标签: reactjs react-hooks gatsby use-context

使用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, selectedNote, setSelectedNote, addNewNote } = notesContext
  addNewNote(initNote)
...
}

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

谢谢!

1 个答案:

答案 0 :(得分:1)

您的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