我使用
目前,在用户界面上,它显示正在被删除,但当页面刷新后,它还会重新出现,因为它仍然存在于localStorage中。
我已经尝试在我的
以下是翻译的结果:
localStorage.setItem
和localStorage.getItem
存储API中的数据(在我的情况下是设备),以便在页面重置时保持持久化。当点击设备时,它会被存储到购物袋中。 当用户在购物袋中单击设备时,我希望它能够“删除”并从本地存储中移除。目前,在用户界面上,它显示正在被删除,但当页面刷新后,它还会重新出现,因为它仍然存在于localStorage中。
我已经尝试在我的
removeDevice
函数中使用localStorage.removeItem(deviceTitle)
,但似乎没有起作用。这是因为我在componentDidMount
中使用了localStorage.getItem
吗?如果是这样,我该如何改变它,使removeItem
函数可以正常工作?
addDevice()
是通过onClick函数调用的(如果需要查看代码部分,请告诉我)。 addDevice = (e, deviceTitle) => {
const array = Array.from(this.state.bag);
if (array.indexOf(deviceTitle) === -1) {
array.push(deviceTitle);
} else {
return;
}
localStorage.setItem("list", JSON.stringify(array));
this.setState({
bag: array
});
};
在这里,设备应该从本地存储中移除
removeDevice = (e, deviceTitle) => {
this.setState(prevState => ({
bag: prevState.bag.filter(d => d !== deviceTitle)
}));
localStorage.removeItem(deviceTitle);
};
这是我的componentDidMount()函数,设备会在此处存储。
componentDidMount() {
this.search("");
const storedList = JSON.parse(localStorage.getItem("list"));
console.log(storedList);
const bag = storedList;
this.setState({ bag });
}
下面添加了更多代码:
render() {
return (
<div>
<form>
<input
type="text"
placeholder="Search for devices..."
onChange={this.onChange}
/>
{this.state.devices.map(device => (
<ul key={device.title}>
<p>
{device.title}{" "}
<i
className="fas fa-plus"
style={{ cursor: "pointer", color: "green" }}
onClick={e => this.addDevice(e, device.title)}
/>
</p>
</ul>
))}
</form>
{this.state.bag.map(device => (
<p key={device.title}>
{device}
<i
className="fas fa-times"
style={{ cursor: "pointer", color: "red" }}
onClick={e => this.removeDevice(e, device)}
/>
</p>
))}
<button onClick={e => this.removeAll(e)}>Remove all</button>
</div>
);
}
}
以下是翻译的结果:
这是它的屏幕截图: 本地存储中的项目, 在 UI 中删除后的项目 但是当我重置页面时,它会恢复到第一张图片,因为设备没有从localStorage中删除。
setState
不会立即更新状态,因此您应该在其回调参数中更新localStorage
,请参见 https://reactjs.org/docs/react-component.html?utm_source=caibaojian.com#setstate - Oblosys