我想从数组中删除最后一项,然后重新渲染,但我似乎不能在不使用过滤器的情况下让它工作。但在我的情况下,我认为不需要过滤器,因为我总是会删除最后一项,所以我使用pop()
const CustomInput = (): JSX.Element => {
const [inputValue, setInputValue] = useState<string>("");
const [items, setitems] = useState<string[]>(['1', '2']);
const handleKeyDown = (e: any) => {
if (items.length && e.keyCode === 8 && inputValue === "") {
const newitems = items;
newitems.pop();
/* what is wrong here */
console.log('newitems', newitems)
setitems(newitems);
}
};
const handleChange = (e: React.SyntheticEvent<HTMLInputElement>) => {
const target = e.target as HTMLInputElement;
setInputValue(target.value);
};
return (
<div>
{items.map((oo, index) => (
<div >
<span>
{oo}
</span>
</div>
))}
<input
autoFocus
type="text"
value={inputValue}
onKeyDown={handleKeyDown}
onChange={handleChange}
/>
</div>
);
};
https:/stackblitz.comeditreact-ts-hxzcpt。
有什么问题吗?
你是将同一个状态数组引用突变并保存回状态,react认为这是一个 "非操作",即数组引用是一样的,所以它在重新渲染时就放弃了。你可以使用 slice
将第0到第2到最后一个元素复制到一个新的数组引用中,基本上每次回调调用都会将最后一个元素切掉。
const handleKeyDown = (e: any) => {
if (items.length && e.keyCode === 8 && inputValue === "") {
setitems(items.slice(0, -1)); // index 0 to last - 1
}
};
你是在直接突变状态,这里有一个解决方案。
const newitems = [...items];
newitems.pop();