我正在使用 react-native 并从 API 中获取一些数据。都好。当我尝试将数据显示到我的然后我只能显示第一个像 data.artistName,但是当我尝试访问 data.graphics.dvd 时我收到错误“TypeError: undefined is not an object (evaluating 'data.graphics .dvd')"
图形是一个对象。
const Videos = () => {
const [isLoading, setLoading] = useState(true);
const [data, setData] = useState([]);
useEffect(() => {
const fetchPost = async () => {
fetch('https://myurl.com/api/title/5fac58f764e6710/')
.then((response) => response.json())
.then((json) => setData(json))
.catch((error) => console.error(error))
.finally(() => setLoading(false));
}
fetchPost();
}, []);
return (
<View style={styles.wrapper}>
<Text style={styles.title}>{data.artistName}{data.graphics.dvd}</Text>
</View>
)
};
答案 0 :(得分:1)
在初始状态下,您将 data
定义为空数组:
const [data, setData] = useState([]);
这意味着在第一次渲染时,data == []
此时,当您访问 data.artistName
时,其计算结果为 undefined
,但不会导致类型错误。
但是,当 data === []
,然后您尝试获取 data.graphics.dvd
时,您会收到类型错误,因为 graphics
未定义,而您正试图从中获取 dvd
要解决这个问题,请在渲染该部分之前检查 data
实际上是否包含某些内容:
{(data.artistName && data.graphics) ? <Text style={styles.title}>{data.artistName}{data.graphics.dvd}</Text> : null}
处理此问题的另一种方法(在您进入 return 语句正文之前)是检查 data
并在没有任何内容时执行不同的返回:
if (loading) {
return <Text>Loading...</Text>
}
return (<View/>) //your normal return
这一切都基于您的 API 调用返回后存在 data.graphics
,原始帖子的评论者提到了这一点。