问题描述
使用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>
);
}