React空数组循环遍历

huangapple go评论66阅读模式
英文:

React empty array loop through

问题

I need help with a React.js problem.
我需要帮助解决一个React.js问题。

I am making a request with user input on a search bar I am using the hook useDebounce and when the user clears the input field after they got a result back. The array data becomes empty and the map function cannot run on an empty array.
我正在使用搜索栏上的用户输入发出请求,我正在使用useDebounce钩子,当用户在得到结果后清空输入字段时,数组数据变为空,map函数无法在空数组上运行。

How do I check for empty array when the user clears out the input field.
当用户清空输入字段时,我如何检查空数组。

App.jsx

// debounced query
  let {debouncedQuery} = useContext(DataContext)

useEffect(() => {
    // get the images of the breed that is chosen
    const loadByBreed = async (value: string) => {
      if (!debouncedQuery) return
      
      try {
        const response = await fetch(`https://dog.ceo/api/breed/${value}/images`)
        const data = await response.json()
        console.log(data)
        setImagesOfABreed(data.message)
      } catch (error) {
        const err = error as Error
        console.log(err.message)
      }
    }

    loadByBreed(debouncedQuery);

  }, [debouncedQuery])

{ debouncedQuery &&  imagesOfABreed?.length ? imagesOfABreed.map((data) => {
            return (
              <Card key={data} img={data} />
            )
          }) : <p>Nothing</p>}

App.jsx

// 防抖查询
let {debouncedQuery} = useContext(DataContext)

useEffect(() => {
    // 获取所选择品种的图像
    const loadByBreed = async (value: string) => {
      if (!debouncedQuery) return
      
      try {
        const response = await fetch(`https://dog.ceo/api/breed/${value}/images`)
        const data = await response.json()
        console.log(data)
        setImagesOfABreed(data.message)
      } catch (error) {
        const err = error as Error
        console.log(err.message)
      }
    }

    loadByBreed(debouncedQuery);

  }, [debouncedQuery])

{ debouncedQuery &&  imagesOfABreed?.length ? imagesOfABreed.map((data) => {
            return (
              <Card key={data} img={data} />
            )
          }) : <p>Nothing</p>}

(Note: The code remains in English as requested.)

英文:

I need help with a React.js problem.

I am making a request with user input on a search bar I am using the hook useDebounce and when the user clears the input field after they got a result back. The array data becomes empty and the map function can not run on an empty array.

my question is

How do I check for empty array when the user clears out the input field.

App.jsx


// debounced query
  let {debouncedQuery} = useContext(DataContext)

useEffect(() =&gt; {
    // get the images of the breed that is choosen
    const loadByBreed = async (value: string) =&gt; {
      if (!debouncedQuery) return
      
      try {
        const response = await fetch(`https://dog.ceo/api/breed/${value}/images`)
        const data = await response.json()
        console.log(data)
        setImagesOfABreed(data.message)
      } catch (error) {
        const err = error as Error
        console.log(err.message)
      }
    }


    loadByBreed(debouncedQuery);

  }, [debouncedQuery])


{ debouncedQuery &amp;&amp;  imagesOfABreed?.length ? imagesOfABreed.map((data) =&gt; {
            return (
              &lt;Card key={data} img={data} /&gt;
            )
          }) : &lt;p&gt;Nothing&lt;/p&gt;}

答案1

得分: 2

问题实际上是在为API调用形成获取URL时出现的。当用户清空输入字段时,该值变为空字符串。因此,URL变成了这样:https://dog.ceo/api/breed//images。请注意URL中的双斜杠,因为空字符串在'value'中。

在这种情况下,API确实提供了响应,但响应中的'message'属性的内容是一个字符串。请注意,数组和字符串原型都有'length'属性。在这种情况下,在渲染组件的UI元素时,条件得到满足,代码尝试在字符串上运行map函数,这就是失败的原因所在。

修复它的一种方法是在'try-catch'块之前添加以下片段:

if(!value) {
    setImagesOfABreed([]);
    return;
}
英文:

The problem actually originates at the formation of the fetch url for the API call. When the user empties the input field, the value becomes an empty string. So, the URL becomes something like this: https://dog.ceo/api/breed//images. Note the double-slashes in the URL because of the empty string in 'value'.

The API does provide a response in this case but the contents of the 'message' property in the response is a string. Note that both Array and String prototypes have the 'length' property. In this case, the condition while rendering the component's UI elements is satisfied and the code tries to run the map function on a string and that is where it fails.

One of the ways to fix it would be to add this snippet before the try-catch block:

if(!value) {
    setImagesOfABreed([]);
    return;
}

huangapple
  • 本文由 发表于 2023年3月21日 01:09:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/75793294.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定