反应不输出Axios在不良API呼叫上遇到错误,而是会遇到JavaScript错误

发布于 2025-02-11 15:15:21 字数 1728 浏览 1 评论 0原文

当我向不应该返回任何内容的API提出不良请求时,它会崩溃我的应用,但不会机。我的组件之一。我似乎找不到错误的原因。

地图的组件:

const Viewer=({poem})=>{
    return(
        <>
        {
            poem.map((item) => {
                let author = item.author
                let title = item.title
                let lines = item.lines
                if (author!= undefined && title!= undefined) {
                    return(
                        <>
                        <div className="viewer">
                            <div className="author">{author}</div>
                            <div className="title">{title}</div>
                            <div className="lines">
                                {lines.map((line) =>
                                    <div>{line}</div>
                                )}
                            </div>
                        </div> 
                        </>
                    )
                }
            })
        }
        </>
    )
}

之后我的页面变为空白,直到我重新加载它,然后收到3个错误消息,说诗图不是函数。

这是我获取API的方式:

const searchPoem= (event) => {
    if(event.key==="Enter")
    {
      axios.get("https://poetrydb.org/"+option+"/"+search+"/all")
      .then(res=>setPoemData(res.data))
      .catch((err) => {
        if (err.response) {
          console.log(err.response.data)
          console.log(err.response.status)
          console.log(err.response.headers)
        } else if (err.request) {
          console.log(err.request)
        } else {
          console.log('Error', err.message)
        }
      })
    }
  }

将结果放入使用我的查看器组件生成卡的DIV中

When I make a bad request to my API that should not return anything, it crashes my app but doesn't console.log any of the error messages I set up for axios, instead I get a bunch of errors regarding the map I used in one of my components. I cannot seem to find the cause of the error.

The component with the map:

const Viewer=({poem})=>{
    return(
        <>
        {
            poem.map((item) => {
                let author = item.author
                let title = item.title
                let lines = item.lines
                if (author!= undefined && title!= undefined) {
                    return(
                        <>
                        <div className="viewer">
                            <div className="author">{author}</div>
                            <div className="title">{title}</div>
                            <div className="lines">
                                {lines.map((line) =>
                                    <div>{line}</div>
                                )}
                            </div>
                        </div> 
                        </>
                    )
                }
            })
        }
        </>
    )
}

Afterwards my page goes blank until I reload it and I get 3 error messages saying that poem.map is not a function.

Here is how I am fetching the API:

const searchPoem= (event) => {
    if(event.key==="Enter")
    {
      axios.get("https://poetrydb.org/"+option+"/"+search+"/all")
      .then(res=>setPoemData(res.data))
      .catch((err) => {
        if (err.response) {
          console.log(err.response.data)
          console.log(err.response.status)
          console.log(err.response.headers)
        } else if (err.request) {
          console.log(err.request)
        } else {
          console.log('Error', err.message)
        }
      })
    }
  }

The results get put into a div that generates a card using my viewer component

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

憧憬巴黎街头的黎明 2025-02-18 15:15:21

在非阵列变量上被调用,它将引发错误。

由于该页面在不良API调用后破裂,因此防止它的一种方法是检查poem是使用 array.isarray() 在执行poem.map()。

const Viewer = ({ poem }) => {
  return (
    <>
      {Array.isArray(poem) // Add extra type checking before rendering
        ? (
          poem.map((item) => {
            let author = item.author;
            let title = item.title;
            let lines = item.lines;
            if (author != undefined && title != undefined) {
              return (
                <>
                  <div className="viewer">
                    <div className="author">{author}</div>
                    <div className="title">{title}</div>
                    <div className="lines">
                      {lines.map((line) => (
                        <div>{line}</div>
                      ))}
                    </div>
                  </div>
                </>
              );
            }
          })
        )
        : null // or a error message component
      }
    </>
  );
};

When .map() is called on non-array variables, it will throws error.

Since the page breaks after a bad API call, one way to prevent it is to check if poem is an Array using Array.isArray() before performing poem.map().

const Viewer = ({ poem }) => {
  return (
    <>
      {Array.isArray(poem) // Add extra type checking before rendering
        ? (
          poem.map((item) => {
            let author = item.author;
            let title = item.title;
            let lines = item.lines;
            if (author != undefined && title != undefined) {
              return (
                <>
                  <div className="viewer">
                    <div className="author">{author}</div>
                    <div className="title">{title}</div>
                    <div className="lines">
                      {lines.map((line) => (
                        <div>{line}</div>
                      ))}
                    </div>
                  </div>
                </>
              );
            }
          })
        )
        : null // or a error message component
      }
    </>
  );
};
迷你仙 2025-02-18 15:15:21

尝试记录组件中的变量诗。

如果API什么都没返回,那么在这种情况下将不存在变量诗,因此诗歌也不会。

Have a look into conditional rendering - https://reactjs.org/docs/conditional-rendering.html

您可以在渲染功能中使用与下面类似的内容来处理此问题。

poem && Viewer(poem)

Try log the variable poem within the component.

If an API returns nothing, the variable poem will not exist in this context, and therefore neither will poem.map.

Have a look into conditional rendering - https://reactjs.org/docs/conditional-rendering.html

You could handle this in the rendering function with something similar to the below.

poem && Viewer(poem)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文