reactjs - 在我的 React 项目中未捕获 TypeError : Object is not iterable (cannot read property Symbol(Symbol. 迭代器))

标签 reactjs react-hooks react-context use-context

我是上下文 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;

最佳答案

如果您正在编写自己的 React Hook (使用... 函数),那么这可能会发生,具体取决于您在自定义 Hook 中返回值的方式。

例如,返回一个数组需要一个数组:

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}

关于reactjs - 在我的 React 项目中未捕获 TypeError : Object is not iterable (cannot read property Symbol(Symbol. 迭代器)),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71090914/

相关文章:

javascript - 使用 redux-form 验证检索错误

reactjs - react-hook-form Controller 问题

javascript - React useLocation hook 的替代方案用于基于 url 的页面更新?

reactjs - 将 React 17 更新为 React 18 - Typescript - ReactNode 类型的子代不再处理 `void` 的内联条件渲染

javascript - 为什么我的容器组件不能正确接收 Async Await 的结果?

javascript - 为什么我的时钟代码会减慢我的网站速度

javascript - 在 react 中结合两个对象,到目前为止没有成功

reactjs - 在组件之间路由时如何保持 React 新的 Context API 状态?

reactjs - 使用 Context API 示例解释 React 高阶组件

reactjs - "Missing return type on function"样式组件插值函数错误