简体   繁体   English

单击我的提交按钮,存储在 localstorage 中的数组不会添加新项目,而是在使用 react 时被替换

[英]onclick of my submit button, the array stored in localstorage does not add the new item but is replaced while using react

I'm trying to add data from a single input field to an array which i want to store in localstorage but when i submit input button, the item is stored at first but if i try to store a second item, the array previous item is replaced with the newly typed item data instead of adding to it like i'd expect an array to behave.我正在尝试将单个输入字段中的数据添加到我想存储在 localstorage 中的数组中,但是当我提交输入按钮时,该项目首先存储,但如果我尝试存储第二个项目,则数组上一个项目是替换为新输入的项目数据,而不是像我期望的数组那样添加到它。 i don't understand this behaviour.我不明白这种行为。 i will really really appreciate a detailed explanation since i'm using react to do this.我真的非常感谢详细的解释,因为我正在使用 react 来做到这一点。 This is my code below这是我下面的代码

input field输入栏

    import React from "react";
import "./addoption.css";

function AddOption({ validateOption }) {
  const handleAddoption = (e) => {
    e.preventDefault();
    const inputValue = e.target.elements[0].value.trim();
    validateOption(inputValue);
    e.target.elements[0].value = "";
  };

  return (
    <div className="addoption">
      <form onSubmit={handleAddoption}>
        <input type="text" name="list" />
        <button>Add Option</button>
      </form>
    </div>
  );
}

export default AddOption;

*this is my code to add the input data to the localstorage * *这是我将输入数据添加到localstorage的代码*


  const handleAddoption = (option) => {
    if (!option) {
      return setErrorhandler("Enter valid value to add item");
    } else if (listItems.options.indexOf(option) > -1) {
      return setErrorhandler("This option already exists!");
    }
    const array = localStorage.getItem("Options");
    let items = [];
    if (array) {
      items = JSON.parse(array);
    }
    let storedArray = JSON.stringify(items.push(option));

    localStorage.setItem("options", storedArray);

    setListItems({ options: items });
  };
``

    

Array.prototype.push certainly mutates the array, but it's return value isn't the array, it's the new length of the array. Array.prototype.push当然会改变数组,但它的返回值不是数组,而是数组的新长度。 You may want to do the mutation separate from the JSON serializing.您可能希望将变异与 JSON 序列化分开进行。

The reason for the overwriting is because you're using two different storage keys for getting and setting.覆盖的原因是因为您使用两个不同的存储密钥进行获取和设置。 You are not getting what was stored so you are only appending new data to an empty array.您没有获得存储的内容,因此您只是将新数据附加到空数组中。 Make sure you also use the same key to both retrieve and set the localStorage.确保您还使用相同的密钥来检索设置 localStorage。

const handleAddoption = (option) => {
  if (!option) {
    return setErrorhandler("Enter valid value to add item");
  } else if (listItems.options.indexOf(option) > -1) {
    return setErrorhandler("This option already exists!");
  }
  const array = localStorage.getItem("options");
  let items = [];
  if (array) {
    items = JSON.parse(array);
  }

  items.push(option);

  localStorage.setItem("options", JSON.stringify(items));

  setListItems({ options: items });
};

A more optimal solution would be to read in and initialize the options state from localStorage, and use an useEffect hook to just persist state updates back to localStorage.更优的解决方案是localStorage 读入并初始化options状态,并使用useEffect钩子将状态更新持久化localStorage。 This way is a little easier to manage.这种方式管理起来容易一些。

Example:例子:

const initializeState = () => ({
  // ... other listItems initial state
  options: JSON.parse(localStorage.getItem("options")) || [],
});

const [listItems, setListItems] = useState(initializeState());

useEffect(() => {
  localStorage.setItem("options", JSON.stringify(listItems.options));
}, [listItems.options]);

const handleAddoption = (option) => {
  if (!option) {
    return setErrorhandler("Enter valid value to add item");
  } else if (listItems.options.indexOf(option) > -1) {
    return setErrorhandler("This option already exists!");
  }
  
  setListItems(prevState => ({
    ...prevState
    options: prevState.options.concat(option),
  }));
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM