【问题标题】:fetching external APIs with React js使用 React js 获取外部 API
【发布时间】:2021-04-03 23:45:07
【问题描述】:

如果我在 Visual Studio 代码上单击保存,则此代码 有效。但是当我在浏览器中刷新页面(对 API 的新调用)时,它给了我这个错误:

“TypeError: 无法读取未定义的属性‘集合’”

import React from 'react'

export default function Apitest() {

const [shows, setShows] = React.useState([]);

var myHeaders = new Headers();
myHeaders.append("Authorization", "Basic xxxxxx3456789");

var requestOptions = {
  method: 'GET',
  headers: myHeaders,
  redirect: 'follow'
};

React.useEffect(() => {
    fetch("https://api.vhx.tv/collections", requestOptions)
    .then(response => response.text())
    .then(result => setShows(JSON.parse(result)))
    .catch(error => console.log('error', error));
}, [])


    return (
        <div>
            <h1>{shows._embedded.collections[0].name} is a great show!</h1>
        </div>
    )
}

我认为问题在于我需要进行异步调用。

【问题讨论】:

    标签: javascript reactjs api


    【解决方案1】:

    您所做的是将shows 变量最初设置为array,然后在useEffect 中的asynchronous call 之后为其分配object

    由于shows 存在于_embedded 对象的collections 数组中,您可能希望将collections 数组存储在shows 中,如下所示:

    React.useEffect(() => {
    fetch("https://api.vhx.tv/collections", requestOptions)
    .then(response => response.text())
    .then(result => setShows([...JSON.parse(result)._embedded.collections]))
    .catch(error => console.log('error', error));
    }, []);
    

    当显示show 时,您可能想要这样做:

    return (
        <div>
            <h1>{shows.length && shows[0].name} is a great show!</h1>
        </div>
    )
    

    【讨论】:

      猜你喜欢
      • 2021-02-12
      • 2021-11-14
      • 2022-08-13
      • 1970-01-01
      • 2015-06-03
      • 2019-01-05
      • 1970-01-01
      • 1970-01-01
      • 2019-03-20
      相关资源
      最近更新 更多