[英]useContext is not a function or its return value is not iterable
I get the following error when using const [state, setState] = useContext(Context)
:使用const [state, setState] = useContext(Context)
时出现以下错误:
useContext is not a function or its return value is not iterable
Not sure why as I've done this multiple times before.不知道为什么,因为我以前做过多次。 This is my set up:这是我的设置:
My State.jsx
file:我的State.jsx
文件:
import { createContext, useState } from "react";
export const Context = createContext()
const initialState = {
tasks: {}
}
const State = ({children}) => {
const [state, setState] = useState(initialState)
return (
<Context.Provider value={[state, setState]}>
{children}
</Context.Provider>
)
}
export default State;
Used as a wrapper in App.jsx
:在App.jsx
中用作包装器:
import State from './state'
import TaskList from './components/TaskList'
const App = () => {
return (
<State>
<TaskList />
</State>
)
}
export default App;
Trying to access the state in TaskList.jsx
:尝试访问TaskList.jsx
中的 state:
import { useContext } from 'react';
import { Context } from '../State';
const TaskList = () => {
const [state, setState] = useContext(Context)
return (
<>
<h1>Task list</h1>
</>
)
}
export default TaskList
Which returns the error specified before, any ideas on what I'm doing wrong?哪个返回之前指定的错误,关于我做错了什么的任何想法?
const Context = createContext([initialState, () => {}])
Supply a dummy default value to createContext
should fix the problem.为createContext
提供一个虚拟默认值应该可以解决这个问题。
State.jsx
import { createContext, useContext, useState } from "react";
const Context = createContext();
const initialState = {
tasks: {}
};
const State = ({ children }) => {
const [state, setState] = useState(initialState);
return (
<Context.Provider value={[state, setState]}>{children}</Context.Provider>
);
};
export default State;
export const useStateContext = () => useContext(Context);
TaskList.jsx
import { useStateContext } from "./State";
const TaskList = () => {
const [state, setState] = useStateContext();
return (
<>
<h1>Task list</h1>
<pre>{JSON.stringify(state)}</pre>
</>
);
};
export default TaskList;
Wow working fine...哇工作正常...
The issue was in App.jsx
:问题出在App.jsx
中:
import State from './state'
import TaskList from './components/TaskList'
const App = () => {
return (
<State>
<TaskList />
</State>
)
}
export default App;
My state is called State.jsx
, but as you can see I'm importing it from './state'
without capital S
.我的 state 称为State.jsx
,但如您所见,我是从没有大写S
'./state'
导入它的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.