简体   繁体   English

当我想将商品添加到购物车时,state.cartItems 不可迭代

[英]state.cartItems is not iterable when i want to add a item to cart

I'm trying to learn mern stack and redux by making a small e-commerce website and i have this state.cartItmes is not iterable error in redux action and i have no idea what is causing it or how to fix it我正在尝试通过制作一个小型电子商务网站来学习 mern stack 和 redux,我有这个 state.cartItmes is not iterable error in Z7490FE17CAEC373F2299D65B6E20E880

So because i hope one day i will became a Frontend developer i'm doing what a developer does...i'm asking you guys what i did wrong in my spagetti code所以因为我希望有一天我会成为一名前端开发人员,所以我正在做开发人员所做的事情......我在问你们我在意大利面条代码中做错了什么

Cart Reducer推车减速机

export const cartReducer = (state = { cartItems: [] }, action) => {
  if (action.type === "ADD_TO_CART") {
    return { cartItems: [...state.cartItems, action.payload] };
  }

  return state;
};

Cart Action购物车动作

import axios from "axios";

export const addToCart = (id) => async (dispatch, getState) => {
  try {
    const { data } = await axios.get(`/products/${id}`);

    dispatch({ type: "ADD_TO_CART", payload: data });

    localStorage.setItem(
      "cartItems",
      JSON.stringify(getState().cart.cartItems)
    );
  } catch (error) {
    console.log(error.message);
  }
};

Cart component购物车组件

import React, { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { addToCart } from "../actions/CartActions";
import { useParams } from "react-router-dom";

const Cart = () => {
  const dispatch = useDispatch();
  const { id } = useParams();

  const cart = useSelector((state) => state.cart);
  const { cartItems } = cart;
  console.log(cartItems);

  useEffect(() => {
    dispatch(addToCart(id));
  }, [dispatch, id]);

  return (
    <section>
      <div className="cart">
        <div className="cart-items">Cart</div>
        <div className="buy-items"></div>
      </div>
    </section>
  );
};

export default Cart;

After analyzing your code, I think the issue may be the empty array that you initially set.分析您的代码后,我认为问题可能是您最初设置的空数组。 You should try using some default value as initial value, I think this should solve the issue.您应该尝试使用一些默认值作为初始值,我认为这应该可以解决问题。

Also, it is generally not a good practice to put async logic inside a reducer.此外,将异步逻辑放在减速器中通常不是一个好习惯。 You may want to implement some middleware for this.您可能需要为此实现一些中间件。 Here's some more info on it: https://redux.js.org/tutorials/fundamentals/part-6-async-logic#using-middleware-to-enable-async-logic这里有一些关于它的更多信息: https://redux.js.org/tutorials/fundamentals/part-6-async-logic#using-middleware-to-enable-async-logic

to add an empty array helped me, thx添加一个空数组帮助了我,谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 未处理的拒绝(TypeError):state.cartItems 未定义 - Unhandled Rejection (TypeError): state.cartItems is undefined 我想将对象推送/添加到本机状态(无效的尝试来传播不可迭代的实例) - I want to push / add object to the state react native (invalid attempt to spread non iterable instance) 我如何将 api 中的数据转换为数组我无法使用 map function 所以我想将 cart.cartItems 转换为数组 - how do i turn data from my api to array i cant use map function so i want to turn cart.cartItems into an array 单击按钮时无法将商品添加到购物车 - Cannot add item to cart when click on the button 当我想从购物车中删除商品时超出了最大更新深度 - Maximum update depth exceeded when I want to remove item from cart 使用反应将项目添加到购物车页面(仅使用 this.state ) - add item to cart page with react ( only with this.state ) 当我从状态中删除项目时,组件不会重新渲染,但是当我添加项目时,它不会重新渲染 - component dont rerender when I remove item from state but it rerender when I add item TypeError:无法解构“cart”的属性“cartItems”,因为它未定义 - TypeError: Cannot destructure property 'cartItems' of 'cart' as it is undefined 我获取了一个数组并想将它添加到我的状态 - I fetched an array and want to add it to my state 如何将商品添加到购物车 - How to add an item to the cart
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM