gpt4 book ai didi

reactjs - typescript 错误 : must have a '[Symbol.iterator]()' method that returns an iterator when using react usereducer hook in context-why?

转载 作者:行者123 更新时间:2023-12-05 03:44:53 25 4
gpt4 key购买 nike

我使用的是 typescript,不太熟悉,当我使用 context 和 useReducer 钩子(Hook)时出现以下错误 - 特别是对于我的调度方法,我得到了这个:

contextProps must have a '[Symbol.iterator]()' method that returns an iterator.

我试图研究它,但不知道该怎么做。我想这是因为 const [state, dispatch] = useContext(GlobalState);因为数组,我需要指定一些东西。此外,我得到一个 ts err for value in

  <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>
);
};

最佳答案

您提供的代码似乎有一些问题。

首先,我将从添加更多类型开始。
特别是reducer的参数和输出和 const [state, dispatch] = useReducer(reducer, initialState); (注意:我假设 reducer 在这里是小写的,尽管它在您的代码示例中是 Reducer

接下来,我认为与您的使用方式相比,您的上下文定义存在问题。
如果您想同时提供 statedispatch给您的提供者(如 <GlobalState.Provider value={[state, dispatch]}> 所示,那么我希望您的上下文定义看起来更像这样:

interface Context {
state: {
show: boolean;
posts: string[];
//...
};
dispatch: React.Dispatch<any>; // I don't know what any should be in your case
}

请注意:

  • 您的提供商将更改为: <GlobalState.Provider value={{state, dispatch}}> .
  • 用法将更改为:const {state, dispatch} = useContext(GlobalState);

如果您确实想使用 [state, dispatch]作为上下文的输出,那么你应该使用类似 type Context = [{show: boolean; posts: string[];}, React.Dispatch<any>] 的类型而不是 interface .

最后,像... must have a '[Symbol.iterator]()' method that returns an iterator.这样的错误通常意味着您正在迭代(使用 forwhile ……)一个不是可以迭代类型的对象。可以迭代的类型的一个例子是 Array。 .
如果您需要有关最后一个错误的更多指导,那么如果您准确指定此错误发生的位置,将会有所帮助。

关于reactjs - typescript 错误 : must have a '[Symbol.iterator]()' method that returns an iterator when using react usereducer hook in context-why?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66184784/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com