【发布时间】:2021-11-23 21:31:12
【问题描述】:
Foll 是代码的大纲。我的“cartSize”已经过时了。
function CartComp(props) {
const [cartSize, setCartSize] = useState(0);
const cartList = useSelector((state) => state.cart.cartItems);
useEffect(() => {
setCartSize(() => {
return cartList.length;
});
}, [cartList]);
const onClickAddBtn = (cartObj) => {
if (cartSize > 4) { // outdated state
alert(`cannot add more than ${cartSize} items`);
}
}
<button
onClick={onClickAddBtn.bind(this, cartObj)}
>
Add
</button>
}
基本上,在点击 时,需要获取cartSize 以用于逻辑目的。
useSelector() 给出一个数组cartList,其length 设置为setCartSize。
所以,当cartSize 被访问时,它正在赋予价值,落后一步。即点击<button>,cartList 是最新的,但cartSize 是前一个值的值。
如何管理这个?如何在点击事件处理程序中使用useSelector() 的值?
EDIT-1:
// robo-list.js
const cartList = useSelector((state) => state.robo.cartItems);
{galleryItems.map((robo) => {
<div>
<CartButton list={cartList} item={robo} />
</div>
...
// 机器人画廊.js
import { useDispatch } from "react-redux";
import Button from "@mui/material/Button";
import AddShoppingCartIcon from "@mui/icons-material/AddShoppingCart";
import { roboActions } from "../store/robo-slice";
function CartButton(props) {
console.log("gal2: ",props.list.length);
const dispatch = useDispatch();
const onClickAddBtn = (len) => {
console.log("gal1: ",len);
if (props.list.length > 2) {
alert(`cannot add more than ${props.cartList.length} material`);
} else {
dispatch(
roboActions.updateCart({
item: props.item,
userAction: "addItemToCart",
})
);
}
};
return (
<Button
variant="outlined"
startIcon={<AddShoppingCartIcon fontSize="small" />}
disabled={props.item.stock === 0}
onClick={onClickAddBtn}
>
Add
</Button>
);
}
export default CartButton;
我已删除 bind() 并将 click 代码分离到另一个名为 robots-gallery.js 的文件中。我正在传递 cartList 并单击项目 robo 进入。
仍然cartList.length 落后一步。 我在这里缺少什么?请帮忙。
完整代码在这里https://codesandbox.io/s/trusting-goldberg-gcivk?file=/frontend/src/components/robo-list.js
编辑 2:
// 机器人列表.js
// 机器人画廊.js
function CartButton(props) {
const cartList = useSelector((state) => state.robo.cartItems);
console.log("gal2: ",cartList.length); //
const dispatch = useDispatch();
const onClickAddBtn = () => {
console.log("gal1: ", cartList.length);
if (cartList && cartList.length > 2) {
alert(`cannot add more than ${cartList.length} items`);
} else {
dispatch(
roboActions.updateCart({
item: props.item,
userAction: "addItemToCart",
})
);
}
};
<Button
variant="outlined"
startIcon={<AddShoppingCartIcon fontSize="small" />}
disabled={props.item.stock === 0}
onClick={onClickAddBtn}
>
Add
</Button>
cartList.length > 2 落后一个更新。
【问题讨论】:
-
为什么不只是 cartList.length?... 为什么要绑定函数?
-
cartList.length给出了陈旧的值,与cartsize的行为相同。我将cartObj绑定到方法,以便将点击值(即cartObj)发送到点击处理程序。
标签: reactjs redux-toolkit