× 类型错误:无法解构'Object(...)(...)'的属性'xxx',因为它未定义



我正在学习react redux,但我面临这个问题,

当我发送"删除"操作时

动作

export const remove = () => ({
type: REMOVE
})

减速器内部开关语句

case REMOVE:
return console.log("removed");
break;

我在删除按钮上使用它

import React from "react";
import { useSelector, useDispatch } from "react-redux";
import { increase, decrease, remove } from "./../actions";
const CartItem = ({ img, title, price, amount }) => {
const dispatch = useDispatch();
const removeItem = () => {
dispatch(remove());
};
return (
<div className="cart-item">
<img src={img} alt={title} />
<div>
<h4>{title}</h4>
<h4 className="item-price">${price}</h4>
{/* remove button */}
<button className="remove-btn" onClick={removeItem}>
remove
</button>
</div>
<div>
{/* increase amount */}
<button className="amount-btn">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20">
<path d="M10.707 7.05L10 6.343 4.343 12l1.414 1.414L10 9.172l4.243 4.242L15.657 12z" />
</svg>
</button>
{/* amount */}
<p className="amount">{amount}</p>
{/* decrease amount */}
<button className="amount-btn">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20">
<path d="M9.293 12.95l.707.707L15.657 8l-1.414-1.414L10 10.828 5.757 6.586 4.343 8z" />
</svg>
</button>
</div>
</div>
);
};
export default CartItem;

操作只是控制台日志,当我单击删除按钮时,它会记录"已删除",然后我得到这个错误

TypeError: Cannot destructure property 'cart' of 'Object(...)(...)' as it is undefined.
CartContainer
E:/React_Projects/Redux-demo/starter-project-redux-tutorial-cart-master/src/components/CartContainer.js:6
3 | import CartItem from "./CartItem";
4 | import { clearCart } from "./../actions";
5 | const CartContainer = () => {
> 6 |   const { cart, total } = useSelector((state) => state);
7 |   const dispatch = useDispatch();
8 |   
9 |   const handleClick = () => {

我在reducer文件中使用了初始状态

import { CLEAR_CART, DECREASE, INCREASE, REMOVE } from "./actions";
// items
import cartItems from "./cart-items";
//initial store
const initialStore = {
cart: cartItems,
total: 1487.00,
amount: 5,
};
const reducer = (state = initialStore, action) => {
switch (action.type) {

我不知道这个错误是什么意思。有人能解释一下并给我看一个解决方案吗。

错误是由以下内容造成的:

case REMOVE:
return console.log("removed");
break;

当你需要返回状态时,你什么也不返回。因此,在调用remove函数并将状态设置为"无"(未定义(之后,从该状态中选择的函数将抛出错误,因为该状态已不存在。这就是为什么这里会出现错误:

const { cart, total } = useSelector((state) => state);

错误表明您无法从状态获取属性"cart",因为状态未定义。

您需要更改减速器,使其在每次操作后返回有效状态。最终你会想真正删除一些东西,但目前这将起作用:

case REMOVE:
console.log("removed");
return state;

相关内容

  • 没有找到相关文章

最新更新