【发布时间】:2019-08-14 10:44:16
【问题描述】:
我目前正在努力迭代从第三方 API 获取的 JSON 对象。您可能会看到,之前并没有真正处理过获取 API。
这是我正在获取的 JSON 文件:
Link to the JSON file
为了获取数据,我使用了如下所示的 useFetch 脚本:
// useFetch.js
import { useState, useEffect } from "react";
import fetch from 'isomorphic-unfetch';
function useFetch(url) {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
async function fetchUrl() {
const res = await fetch(url);
const json = await res.json();
setData(json);
setLoading(false);
}
useEffect(() => {
fetchUrl();
}, []);
return [data, loading];
}
export { useFetch };
我稍后要导出的只是每个角色/冠军的名称(他们本身就是一个对象,包括名称、描述等)
// App.js
import { useState, useEffect } from 'react';
import { useFetch } from "../components/useFetch";
const App = () => {
const [data, loading] = useFetch(
"https://ddragon.leagueoflegends.com/cdn/9.3.1/data/en_US/champion.json"
);
useEffect(() => {
console.log(data)
})
return (
<div>
<ul>
{Object.keys(data.data).map((item, i) => (
<li key={i}> // every character has got an ID as well I'd like to pass here later. The output is just a dummy rn.
<p>{data.data}</p>
</li>
))}
</ul>
</div>
)
}
export default App;
不幸的是,我在尝试转换 JSON 对象 data.data 时遇到了错误,上面写着:TypeError: Cannot convert undefined or null to object
这指向我在 JSX 中的迭代。
我尝试的是针对那些空规则并给它们一个字符串作为结果,例如
if ((typeof Object === null) || (typeof Object === undefined)) {
return '-'
}
或
if ((item === null) || (item === undefined)) {
return '-'
}
但这显然没有帮助。
我会感谢任何提示/优化。
【问题讨论】:
-
我已经看过这个,但我似乎没有正确实施它可能的修复。
-
data.data是未定义还是为空?
标签: javascript json reactjs fetch-api