【发布时间】:2021-07-11 14:27:03
【问题描述】:
状态定义如下:
const [items, setItems] = useState([] as CartItemType[]);
const [id, setId] = useState<number | undefined>();
在这种情况下,id 完全没用。在我的应用中根本不需要它。
但是,如果我尝试更新 items,状态变量不会改变并且 UI 不会重新加载,除非我也会更新 id:
useEffect(() => console.log("reload")); // only fires if I include setId
const clickItem = (item: CartItemType) => {
let tempItems = data;
// @ts-ignore
tempItems[item.id - 1].animation =
"item animate__animated animate__zoomOut";
setItems(tempItems!); // "!" to get rid of ts complaint about possible undefined value
setId(item.id); // nothing happens if I don't include this
};
// ... inside the return, in a map fn
<Item
item={item}
handleAddToCart={handleAddToCart}
clickItem={clickItem}
/>
// inside Item component
<StyledItemWrapper
className={item.animation}
onClick={() => {
clickItem(item); // item = an obj containing an id and an animation property
}}
>
这里为什么需要setId? setItems 不是在做什么?
【问题讨论】:
-
您是否尝试在 setItems([...tempItems]) 上强制使用新数组;或 Array.from(tempItems)。您在项目渲染功能中使用什么作为键?
-
使用
@ts-ignore和!非空断言违背了使用TypeScript 的目的。您应该尝试修复代码而不是消除错误。 -
@EmileBergeron 我同意 - 正在与时间赛跑。
标签: javascript reactjs typescript react-hooks state