如果值的长度为0,如何重置fetch调用?

问题描述 投票:-1回答:2

你好,我在一个输入上有fetch功能,当用户输入内容时,会执行fetch和节流函数。当用户输入内容时,fetch和节流函数将被执行。无论输入的长度是多少,fetch调用都会被执行。所以我必须在值的长度为零时更新fetch调用,因为当值的长度为零时不需要fetch调用。谁能帮我解决这个问题?

const throttling = useCallback(
    throttle(function(value) {
      const myFetch = fetch('http://localhost:8000/api/auto-suggest?input=' + encodeURIComponent(value))
      if (value.length > 0) {
        myFetch.then(response => response.json()).then(setSearchResult)
      } else {
        console.log('is 0')
      }
    }, 500),
    []
  )

function handleChange(event) {
    throttling(event.target.value)
    onChange(event.target.value)
  }
javascript reactjs
2个回答
0
投票

所以你为什么不在开始执行取值函数之前就先检查值的长度呢?或者你可以在开始执行fetch函数之前检查内容是否为空。


0
投票

也许你可以把 fetch 里面 if 语句。试作如下。

if (value.length > 0) {
     const myFetch = fetch('http://localhost:8000/api/auto-suggest?input=' + encodeURIComponent(value));
     myFetch.then(response => response.json()).then(setSearchResult);
} else {
     console.log('is 0');
}

这样一来 fetch 只有在以下情况下才会被执行 value.length > 0 成为 true.

© www.soinside.com 2019 - 2024. All rights reserved.