【发布时间】:2021-05-16 23:13:26
【问题描述】:
我使用的是打字稿,不太熟悉,并且当我使用 context 和 useReducer 挂钩时出现以下错误 - 特别是对于我的调度方法,我得到了这个:
contextProps must have a '[Symbol.iterator]()' method that returns an iterator.
我试图研究它,但不知道该怎么做。我想这是因为 const [state, dispatch] = useContext(GlobalState);由于数组,我需要指定一些东西。 此外,我在价值方面得到了一个 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>
);
};
【问题讨论】:
标签: reactjs typescript