簡體   English   中英

簡化自動建議的設計

[英]Simplify the design for auto-suggestion

我的代碼中有一個相當復雜的結構,它在 const matchSuggestions 中。 此構造負責自動建議。 例如:有幾個男性名字(Adam、Adrian、Arnold、Mike)。 用戶輸入第一個字母“A”並看到自動建議 - Adam、Adrian、Arnold。 然后他輸入字母“D”並保持自動建議 - 亞當,阿德里安。 等等。

是否有可能以某種方式簡化這部分代碼?

const onChange = (e) => {
  const { value } = e.target;
  setInput(value)

  if(value.length < 1) { setSuggestedTags([]); setIsValid([]);return; }
  
  const matchedSuggestions = tagSuggestions.filter((s) => {
    return s.slice(0, 2).search(value.slice(0, 2)) > -1 
        && s.slice(0, 1).search(value.slice(0, 1)) > -1
        && s.slice(0, 3).search(value.slice(0, 3)) > -1
        && !tags.includes(s)
  })
  setSuggestedTags(matchedSuggestions); 

  if (e.target.value) {
    setIsValid(() => /^[1-5][0-9]?[0-9]?$|^100$/.test(e.target.value));
  } else {
    setIsValid(true);
  }
  setInput(value);
};

您可以獲取輸入字符串的長度並將其用作切片的索引。 更好的是,您可以使用startsWith ,如果想要標准化為大寫或小寫,例如

 value = value.toLowerCase();             // normalize
 tagSuggestions.filter(s =>
     s.toLowerCase().startsWith(value) && // or includes(value) in case you want to validate part of the string
     !tags.includes(s)                    // what is this for?
 );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM