开发者问题收集

未捕获的类型错误:对象不可迭代 --> 使用带有 Reducer 的上下文

2022-02-01
2014

我正在学习将 useContext 和 useReducer 结合使用,但出现了一个我还没能弄清楚的错误:

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

它发生在解构 MealItemForm.js 中的上下文之后。我尝试在 createContext 中设置默认值,使用和不使用花括号导入等等。我试图在子组件内调度该函数。有什么想法吗?

MealItemForm.js

import React,{useContext} from 'react';
import MeatContext from '../store/meat-context';
import Input from './Input';
import styles from "./MealItemForm.module.css"

function MealItemForm(props) {
  
  const [meatState,dispatchMeatState]=useContext(MeatContext)
  const handleClick=(event)=>{
event.preventDefault();

  }  
  
  return (
      <form className={styles.form}>
          <Input/>
          <button onClick={handleClick}>+ Add</button>
      </form>
  );
}

export default MealItemForm;

meat-context.js

import React,{useReducer,useState} from 'react';


const MeatContext = React.createContext({meatState:[]});

export function MeatContextProvider(props) {
  const meatReducer = (state, action) => {
    if (action.type === 'ADD_MEAT') {
      return [...meatState];
    }

    return {  };
  };
  
  const [meatState, dispatchMeatState] = useReducer(meatReducer,
    [

    ]
  );
  return (
<MeatContext.Provider value={{meatState:meatState,dispatchMeatState:dispatchMeatState}}>
  {props.children}
</MeatContext.Provider>
  );

  
}
export default MeatContext
2个回答

提供给 Context 的值是一个对象

{meatState:meatState,dispatchMeatState:dispatchMeatState}

但是您在获取值时使用了数组解构

const [meatState, dispatchMeatState ] = useContext(MeatContext)

使用对象解构应该可以解决这个问题,

const { meatState, dispatchMeatState } = useContext(MeatContext)
Badal Saibo
2022-02-01

用{object}重组,而不是[array]解决问题

Ohiare Nathaniel
2022-09-06