0

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

我创建了一个文件,其中包含我的 Context、Provider 和 Consumer

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 应用程序中,所以不确定这是否会导致我不知道的潜在问题。

提前致谢!

4

1 回答 1

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>
  );
}

编辑 sweet-goodall-pnsx0

于 2020-08-11T01:13:13.993 回答