如何减少语法重复(DRY)?

How can I make syntax less repetitive (DRY)?

此应用程序的目的是允许将输入的文本和 URL 保存到 localStorage。可以正常使用,但是有很多重复代码。

例如,localStoredValuesURLStoredVAlues 都来自 localStorage getItemlocalStoredValueslocalStorage 获取以前的输入值,而 URLStoredVAlueslocalStorage.

获取以前的 URL

updateLocalArrayupdateURLArray 使用扩展运算符迭代 of 以前的值并存储新值。

我想让代码更“枯燥”并希望得到建议。

/*global chrome*/

import {useState} from 'react';
import List from './components/List'
import { SaveBtn, DeleteBtn, DisplayBtn, TabBtn} from "./components/Buttons"


function App() {
  const [myLeads, setMyLeads] = useState([]);
  const [leadValue, setLeadValue] = useState({
    inputVal: "",
  });


  //these items are used for  the state of localStorage
  const [display, setDisplay] = useState(false);
  const localStoredValues = JSON.parse(
    localStorage.getItem("localValue") || "[]"
  )
  let updateLocalArray = [...localStoredValues, leadValue.inputVal]

  //this item is used for the state of localStorage for URLS
  const URLStoredVAlues = JSON.parse(localStorage.getItem("URLValue") || "[]")

  const tabBtn = () => {
     chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
       const url = tabs[0].url;
       setMyLeads((prev) => [...prev, url]);

       // update state of localStorage
       let updateURLArray = [...URLStoredVAlues, url];
       localStorage.setItem("URLValue", JSON.stringify(updateURLArray));
     }); 
    setDisplay(false)
  };

  //handles change of input value
  const handleChange = (event) => {
    const { name, value } = event.target;
    setLeadValue((prev) => {
      return {
        ...prev,
        [name]: value,
      };
    });
  };

  const saveBtn = () => {
    setMyLeads((prev) => [...prev, leadValue.inputVal]);
    setDisplay(false);

    // update state of localStorage
    localStorage.setItem("localValue", JSON.stringify(updateLocalArray))
  };

  

  const displayBtn = () => {
    setDisplay(true);
  };

  const deleteBtn = () => {
    window.localStorage.clear();
    setMyLeads([]);
  };

  const listItem = myLeads.map((led) => {
    return <List key={led} val={led} />;
  });

  //interates through localStorage items returns each as undordered list item
  const displayLocalItems = localStoredValues.map((item) => {
    return <List key={item} val={item} />;
  });

  const displayTabUrls = URLStoredVAlues.map((url) => {
    return <List key={url} val={url} />;
  });

  return (
    <main>
      <input
        name="inputVal"
        value={leadValue.inputVal}
        type="text"
        onChange={handleChange}
        required
      />

      <SaveBtn saveBtn={saveBtn} />
      <TabBtn tabBtn={tabBtn} />
      <DisplayBtn displayBtn={displayBtn} />
      <DeleteBtn deleteBtn={deleteBtn} />

      <ul>{listItem}</ul>

      {/* displays === true show localstorage items in unordered list 
          else hide localstorage items */}
      {display && (
        <ul>
          {displayLocalItems}
          {displayTabUrls}
        </ul>
      )}
    </main>
  );
}

export default App

这些键可以声明为 const 并重复使用,而不是传递字符串:

const LOCAL_VALUE = "localValue";
const URL_VALUE = "URLValue";

您可以创建一个从本地存储检索的实用函数,returns 如果缺少默认数组,并解析 JSON:

function getLocalValue(key) {
  return JSON.parse(localStorage.getItem(key) || "[]")
};

然后在检索“localValue”和“URLValue”时将使用它而不是重复逻辑:

const localStoredValues = getLocalValue(LOCAL_VALUE) 

//this item is used for the state of localStorage for URLS
const URLStoredVAlues = getLocalValue(URL_VALUE)

类似地,使用 setter 逻辑:

function setLocalValue(key, value) {
  localStorage.setItem(key, JSON.stringify(value))
}

然后使用它:

// update state of localStorage
let updateURLArray = [...URLStoredVAlues, url];
setLocalValue(URL_VALUE, updateURLArray);


// update state of localStorage
setLocalValue(LOCAL_VALUE, updateLocalArray)