使用 React js 获取外部 API

时间:2021-04-03 23:45:07

标签: javascript reactjs api

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

“类型错误:无法读取未定义的属性“集合””

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>
    )
}

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

1 个答案:

答案 0 :(得分:0)

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

由于 shows 存在于 collections 对象的 _embedded 数组中,您可能希望将 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>
)