reactjs - × TypeError:无法解构'Object(...)(...)'的属性'xxx',因为它是未定义的
问题描述
我正在学习react redux,但我面临这个问题,
当我发送“删除”操作时
行动
export const remove = () => ({
type: REMOVE
})
在 switch 语句中的 reducer
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 = () => {
我在减速器文件中使用了初始状态
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);
该错误表明您无法从 state 中获取属性“cart”,因为 state 未定义。
您需要更改您的减速器,以便它在每次操作后返回有效状态。最终你会想要真正删除一些东西,但现在这会起作用:
case REMOVE:
console.log("removed");
return state;
推荐阅读
- apache-spark - 如何将Id添加到spark中的所有数据框行
- python - 以自定义格式将 Pandas 数据框导出为 CSV
- unity3d - 如果对象不移动,onTriggerEnter2D 只会触发一次
- html - CSS 位置:根据“html”和“body”标签的溢出值在不同浏览器中出现奇怪的行为
- java - java中的松树与for循环
- reactjs - 如何防止用户在使用 jsx 的表单中粘贴特定的特殊字符(仅允许的字符包括 (_ - .)
- jquery - SVG 中的 jQuery .offset() 在 Safari 中不起作用
- python - Twilio 在接收短信时触发 Python 函数
- javascript - 如何从总数中启动复选框组值
- android - 编译未能完成:程序类型已存在:com.google.android.gms.ads.identifier.AdvertisingIdClient$zza