【发布时间】:2019-09-21 09:34:40
【问题描述】:
我使用localStorage.setItem 和localStorage.getItem 来存储来自API 的数据(在我的例子中是设备),以便在页面重置时保持不变。当一个设备被点击时,它会被存储到一个购物袋中。当用户单击包中的设备时,我希望它能够“删除”并从本地存储中删除。
现在它的工作原理是在 UI 上显示它正在被删除,但是当页面刷新时它又回来了,因为它仍在 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>
);
}
}
以下是其外观的屏幕截图: items in local storage, items after being removed in the UI 但是当我重置页面时,它会恢复到第一个图像,因为设备没有从 localStorage 中删除
【问题讨论】:
-
在大多数情况下
setState不会立即更新状态,因此您应该在其回调参数中更新localStorage,请参阅reactjs.org/docs/…
标签: javascript arrays reactjs api storage