[英]TypeError: Cannot destructure property 'cartItems' of 'cart' as it is undefined
Again the same tutorial I have a new problem in the cart I am still new to using react redux so thanks for any help for explained I am creating the list of products ordered and counted (after) to be able to modify them added or canceled同样的教程我在购物车中有一个新问题我仍然是使用 react redux 的新手所以感谢任何帮助解释我正在创建订购和计数的产品列表(之后)以便能够修改它们添加或取消
TypeError: Cannot destructure property 'cartItems' of 'cart' as it is undefined. TypeError:无法解构“cart”的属性“cartItems”,因为它未定义。
import React, { useEffect } from 'react';
import { addToCart } from '../actions/cartActions';
import { useDispatch, useSelector } from 'react-redux';
function CartScreen(props) {
const cart = useSelector(state => state.cart);
const { cartItems } = cart;
const productId = props.match.params.id;
const qty = props.location.search ? Number(props.location.search.split("=")[1]) : 1;
const dispatch = useDispatch();
useEffect(() => {
if (productId) {
dispatch(addToCart(productId, qty));
}
}, []);
return <div className="cart">
<div className="cart-list">
<ul className="cart-list-container">
<li>
<h3>
Shopping Cart
</h3>
<div>
Price
</div>
</li>
{
cartItems.length === 0 ?
<div>
Cart is empty
</div>
:
cartItems.map(item =>
<li>
<div className="cart-image">
<img src={item.image} alt="product" />
</div>
<div className="cart-name">
<div>
Qty:
<select value={item.qty} onChange={(e) => dispatch(addToCart(item.product, e.target.value))}>
{[...Array(item.countInStock).keys()].map(x =>
<option key={x + 1} value={x + 1}>{x + 1}</option>
)}
</select>
</div>
</div>
<div className="cart-price">
${item.price}
</div>
</li>
)
}
</ul>
</div>
<div className="cart-action">
</div>
</div>
}
export default CartScreen;
A default value is needed.需要一个默认值。 Somewhere at top-level modules of store:在商店的顶级模块的某个地方:
const EMPTY_CART = { cartItems: [] }; // To ensure that default value is singleton and avoid useless re-renders
inside component:内部组件:
const cart = useSelector(state => state.cart || EMPTY_CART);
const { cartItems } = cart;
It is better to define default values at reducers level.最好在 reducers 级别定义默认值。 Another approach is to pass defaultValue to createStore
.另一种方法是将 defaultValue 传递给createStore
。
https://redux.js.org/recipes/structuring-reducers/initializing-state https://redux.js.org/recipes/structuring-reducers/initializing-state
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.