node.js - cartItems.map 不是 Redux 中的函数
问题描述
早些时候我遇到了一个错误,错误是我必须添加 items.length>0 来等待它。我再次做了类似的事情,但它显示了一个错误
错误
TypeError: cartItems.map is not a function
CartScreen
E:/College/DA/IWP/Book Fair/frontend/src/Screens/CartPage.js:35
32 | <div>Cost</div>
33 | </li>
34 | {
> 35 | cartItems.length == 0?<div>Empty...</div>:
| ^ 36 | cartItems.map(book =>
37 | <div >
38 | <img src = {book.image} alt = {book.name}/>
购物车页面.js
import React, { useEffect } from 'react';
import { AddToCart } from '../actions/cartActions';
import {useDispatch, useSelector} from 'react-redux';
function CartScreen(props){
// get cart items from redux store
const cart = useSelector(state => state.cart);
//From cart get cartItems
const cartItems = cart;
console.log(cartItems);
// Get book id, so we know what is added
const bookId = props.match.params.id;
const qty = props.location.search?Number(props.location.search.split("=")[1]):1;
const dispatch=useDispatch();
useEffect(() =>{
if(bookId){
dispatch(AddToCart(bookId, qty));
}
},[])
return <div className="cartPage">
{/* <div className="cartList">
<ul className="container">
<li>
<h2>Your Cart</h2>
<div>Cost</div>
</li>
{
cartItems.length == 0?<div>Empty...</div>:
cartItems.map(book =>
<div >
<img src = {book.image} alt = {book.name}/>
<div className = "Details">
<div>{book.name}</div>
<div> Quantity:
<select>
<option value = "1">1</option>
<option value = "2">2</option>
<option value = "3">3</option>
<option value = "4">4</option>
</select>
</div>
</div>
<div> {book.cost}</div>
</div>
)
}
</ul>
</div>
<div className="cartButton">
</div> */}
</div>
}
export default CartScreen;
我创建了一个作为主屏幕的 CartPage.js,具有操作的 CartAction.js,CartReducers.js 我尝试更改所有内容,但仍然无法正确
解决方案
我可以看到您的 redux 的默认状态是这样的:state={cartItems:[]}
并且您正在尝试使用const cartItems = cart
. 您需要使用对象破坏来获取您的购物车物品。因为您使用 useSelector 后的购物车是这样的:cart={cartItems:[]}
只需更改您的 CartPage.js 并替换此行:const {cartItems} = cart
. 让我们看看它是否有效。祝你好运@
PS:如果你想直接保存你的购物车并将它从这个重新格式化为这个cart={cartItems:[]}
,cart=[]
你应该更换你的减速器。第一步是将您的默认状态设置为state=[]
等等...