【问题标题】:useContext returning an empty object in Gatsby applicationuseContext 在 Gatsby 应用程序中返回一个空对象
【发布时间】:2020-08-10 23:43:55
【问题描述】:

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

提前致谢!

【问题讨论】:

  • 您是否将 Provider 添加到您的 App/Root 中?

标签: reactjs react-hooks gatsby use-context


【解决方案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>
  );
}

【讨论】:

  • 是的,就是这样。非常感谢!
猜你喜欢
  • 2015-07-26
  • 1970-01-01
  • 2021-03-31
  • 2014-07-15
  • 2018-08-25
  • 2020-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多