我正在使用TypeScript,对其不是很熟悉,当我使用context和useReducer hook时,出现了以下错误,特别是对于我的dispatch方法,我获得了以下错误:
contextProps must have a '[Symbol.iterator]()' method that returns an iterator.
我试图进行研究,但无法弄清楚该做什么。我想这是由于const [state, dispatch] = useContext(GlobalState);,并且我需要指定某些内容,因为涉及到数组。 此外,我在value处遇到了ts错误。
<GlobalState.Provider value={[state, dispatch]}>
(请见下面的代码)。当我将它定义为数组时,ContextProps 中定义的所有属性都消失了。 希望能得到帮助!
//context.js file
export interface ProjectProps {
projects: string[]
}
export interface ContextProps extends ProjectProps {
show: boolean
posts: string[]
//...
}
const initialState = {
posts: [],
show: false
//...
};
export const GlobalState = React.createContext<ContextProps | null>(
initialState
)
const reducer = (state, action) => {
switch (action.type) {
case "SHOW":
return { ...state, show: !state.show }
default:
return state
}
}
const Store: React.FC<{ children: React.ReactNode }> = ({children}) => {
const [state, dispatch] = useReducer(Reducer, initialState);
return (
<GlobalState.Provider value={[state, dispatch]}>
{children}
</GlobalState.Provider>
)
};
const App = () => {
return (
<Store>
<Header/>
<Blog/>
</Store>
);
};
const Blog = () => {
const [state, dispatch] = useContext(GlobalState);
return (
<div>
<button onClick={dispatch({type: "SHOW"})}></button>
{state.show ? <p>hello</p> : null }
</div>
);
};
const [state, dispatch] = useContext(GlobalState)
。你在这里将一个数组解构成了两个变量。但是GlobalState
的类型来自于React.createContext<ContextProps | null>(initialState)
。它不是一个数组,也不能被迭代。 - Stanislas