Uncaught TypeError: Object is not iterable (cannot read property Symbol(Symbol.iterator)) in my React project

Uncaught TypeError: Object is not iterable (cannot read property Symbol(Symbol.iterator)) in my React project

我是上下文的新手 API,正在尝试让我的代码工作。我收到错误:

Uncaught TypeError: Object is not iterable (cannot read property Symbol(Symbol.iterator))

你们中的一些好心人会帮忙吗?

initialUserState 记录一个如下所示的对象:{name: nanny}

我的上下文文件是:

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 &euro; - 20 &euro;) </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;

我看到的几个问题:

  1. 您正在将上下文提供程序组件 GlobalContext 传递给 useContext 挂钩,const [values, setValues] = useContext(GlobalContext);
  2. 上下文值是一个数组,因此在使用数组解构时,数组元素的顺序很重要。

为上下文使用正确的变量。您可能希望为上下文提供 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);

您的值为:

[
    { ...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);