未捕获的类型错误:我的 React 项目中的对象不可迭代(无法读取属性 Symbol(Symbol.iterator))
我是 context API 的新手,正在尝试让我的代码工作。我收到错误:
Uncaught TypeError: Object is not iterable (cannot read property Symbol(Symbol.iterator))
你们当中有谁能帮我解决这个问题吗?
initialUserState 记录一个如下所示的对象:{name: nanny}
我的 context 文件是:
import { createContext, useState } from "react";
const initialUserState = JSON.parse(localStorage.getItem("user"));
console.log(initialUserState);
const initialFormValues = {
video: "Video.mp4",
hourly: "",
ageRange: [],
car: "",
languages: [],
homework: "",
license: "",
preference: "",
vaccination: "",
radius: "",
booked: "",
fileUpload: "file.jpg",
};
export const Global = createContext();
export default function GlobalContext({ children }) {
const [state, setState] = useState(initialUserState);
const [values, setValues] = useState(initialFormValues); //setting form state
const [radioSelected, setRadioSelected] = useState();
const changeState = (newState = {}) => {
const tempState = { ...state, ...newState };
setState(tempState);
localStorage.setItem("user", JSON.stringify(tempState));
};
return (
<Global.Provider
value={[
{ ...state },
changeState,
values,
setValues,
radioSelected,
setRadioSelected,
]}
>
{children}
</Global.Provider>
);
}
然后,当我从中获取状态时,initialFormValues 不会记录在控制台中:
const HourlyRate = () => {
//context API
const [values, setValues] = useContext(GlobalContext); **//this is where the error is being flagged from**
//handle form value changes
const handleChange = (e) => {
e.preventDefault();
const { name, value } = e.target;
setValues({ ...values, [name]: value });
};
return (
<div className="sub-settings-div">
<Link className="back" to="/video-upload">
<span>
<ArrowBackIcon />
</span>
Back
</Link>
<h3 className="sub-settings-header">{t("common.title")}</h3>
<h2 className="sub-settings-sub-header">{t("hourly.subTitle")}</h2>
<p className="range">(10.45 € - 20 €) </p>
<form className="input">
<TextField
className="input-field"
required
id="outlined-required"
label="Hourly Rate"
name="hourly"
value={values.hourly}
onChange={handleChange}
/>
</form>
<div className="nav-btns">
<Link to="/video-upload" className="prev-link">
<button className="prev">{t("buttons.back")}</button>
</Link>
<Link to="/age-range" className="next-link">
<button className="next">
{t("buttons.next")}
<span>
<ArrowForwardIcon />
</span>
</button>
</Link>
</div>
</div>
);
};
export default HourlyRate;
如果您正在编写自己的 React 钩子(
使用...
函数),那么这可能会根据您在自定义钩子中返回值的方式发生。
例如,返回一个数组需要一个数组:
const [count, setCount, increment] = useCount()
// useCount should return:
return [count, setCount, increment]
同样,返回一个对象需要一个对象:
const {count, setCount, increment} = useCount()
// useCount should return:
return {count, setCount, increment}
两者的任何混合都会导致类似错误:
Uncaught TypeError: object is not iterable (cannot read property Symbol(Symbol.iterator))
例如:
const [count, setCount, increment] = useCount()
// useCount will error if it returns:
return {count, setCount, increment}
您的值是:
[
{ ...state },
changeState,
values,
setValues,
radioSelected,
setRadioSelected,
]
并且此行:
const [values, setValues] = useContext(GlobalContext);
将解构该值(一个数组),但解构数组和对象之间存在一个关键区别:
对于数组,解构是按顺序进行的(与按名称进行的对象不同),这意味着:
values
变量将保存第一个对象
{ ...state }
该对象不可迭代
。
如果您的值将是一个对象:
{
state,
changeState,
values,
setValues,
radioSelected,
setRadioSelected,
}
并且 useContext 将是
const {state,setValues} = useContext(GlobalContext);
我发现几个问题:
-
您正在将上下文提供程序组件
GlobalContext
传递给useContext
钩子,const [values, setValues] = useContext(GlobalContext);
- 上下文值是一个数组,因此在使用数组解构时,数组元素的顺序很重要。
为上下文使用正确的变量。您可能希望为上下文指定
GlobalContext
名称,并将提供程序重命名为
GlobalProvider
。我还建议对上下文值使用对象,以消除数组元素顺序解构问题。
export const GlobalContext = createContext();
export default function GlobalProvider({ children }) {
const [state, setState] = useState(initialUserState);
const [values, setValues] = useState(initialFormValues); //setting form state
const [radioSelected, setRadioSelected] = useState();
const changeState = (newState = {}) => {
const tempState = { ...state, ...newState };
setState(tempState);
localStorage.setItem("user", JSON.stringify(tempState));
};
return (
<Global.Provider
value={{
state,
changeState,
values,
setValues,
radioSelected,
setRadioSelected,
}}
>
{children}
</Global.Provider>
);
}
然后假设您的主
App
组件已正确包装在
GlobalProvider
中,请使用钩子中的对象解构。
const { values, setValues } = useContext(GlobalContext);