从reactjs中的本地存储中删除项目

时间:2018-06-03 08:36:05

标签: javascript reactjs local-storage

这是从 localStorage 中删除项目的正确代码:

onDelete(name) {
        console.log("ProductList.onDelete: ", name);
        let {products} = this.state;
        products = products.filter(product => product.name !== name);
        this.setState({products});
        localStorage.setItem('products', JSON.stringify(products));
}

3 个答案:

答案 0 :(得分:0)

要从本地存储中删除项目,只需运行:

localStorage.removeItem("name of the item")

答案 1 :(得分:0)

@Prometheus是对的。

既然你已经要求ReactJS了,我希望以下小提琴帮助你: https://jsfiddle.net/ghoshnirmalya/eqb9vych/5/

addItem = () => localStorage.setItem("name", this.state.name)

removeItem = () => localStorage.removeItem("name")

我在ReactJS中添加了一个完整的示例。

答案 2 :(得分:0)

    let items =JSON.parse(localStorage.getItem("item"));
    items = items.filter((item) => item.id !== id);
    localStorage.setItem("item", JSON.stringify(items));
    if (items.length === 0) {
      localStorage.removeItem("item");
    }