开发者问题收集

TypeError:无法解构“cart”的属性“cartItems”,因为它未定义

2020-07-08
1678

同样是同样的教程,我在购物车中遇到了一个新问题,我对使用 react redux 还不熟悉,所以感谢任何帮助解释我正在创建订购和计数(之后)的产品列表以便能够修改、添加或取消它们

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;
1个回答

需要默认值。在 store 的顶层模块的某个地方:

const EMPTY_CART = { cartItems: [] }; // To ensure that default value is singleton and avoid useless re-renders

组件内部:

const cart = useSelector(state => state.cart || EMPTY_CART);
const { cartItems } = cart;

最好在 Reducer 级别定义默认值。 另一种方法是将 defaultValue 传递给 createStore

https://redux.js.org/recipes/structuring-reducers/initializing-state

Alexander Alexandrov
2020-08-05