如何解决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>
);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。