React Native调用Quote API时result.content返回undefined问题
React Native调用Quote API返回undefined的解决方法
问题说明
调用https://api.quotable.io/quotes/random接口时,console.log(result)能正常输出数组格式的响应,但console.log(result.content)返回undefined,导致无法展示引用内容。接口返回示例为包含单个引用对象的数组:
[{"_id": "tvXaBe-wkKU", "author": "Octavia E. Butler", "authorSlug": "octavia-e-butler", "content": "Sometimes being a friend means mastering the art of timing. There is a time for silence. A time to let go and allow people to hurl themselves into their own destiny. And a time to prepare to pick up the pieces when it's all over.", "dateAdded": "2020-07-10", "dateModified": "2023-04-14", "length": 229, "tags": ["Friendship"]}]
问题原因
接口返回的是数组类型(即使仅包含一个元素),而你直接在数组对象上访问content属性。数组本身没有content和author属性,因此返回undefined。
修复代码
修改randomQuote函数中处理响应数据的逻辑,先从数组中取出第一个元素,再访问其属性:
import React, { useEffect, useState } from "react"; import { Text, TouchableOpacity, View } from "react-native"; const App = () => { const [Quote, setQuote] = useState("Loading..."); const [Author, setAuthor] = useState("Loading..."); const [isLoading, setIsLoading] = useState(false); const randomQuote = () => { setIsLoading(true); fetch("https://api.quotable.io/quotes/random") .then((res) => { if (!res.ok) { throw new Error(`Failed to fetch: ${res.status}`); } return res.json(); }) .then((result) => { // 取出数组中的第一个引用对象 const quoteData = result[0]; console.log(quoteData.content); setQuote(quoteData.content); setAuthor(quoteData.author); setIsLoading(false); }) .catch((error) => { console.error("Error fetching quote:", error.message); setIsLoading(false); }); }; useEffect(() => { randomQuote(); }, []); return ( <View style={{ flex: 1, justifyContent: "center", alignItems: "center", backgroundColor: "#ADD8E6", }} > <View style={{ width: "90%", backgroundColor: "#fff", borderRadius: 20, padding: 20, }} > <Text style={{ color: "#333", textAlign: "center", fontSize: 26, fontWeight: "600", marginBottom: 20, }} > Quote of the Day </Text> <Text style={{ color: "black", fontSize: 30, fontWeight: "800" }}> " </Text> <Text style={{ color: "purple", fontSize: 16, lineHeight: 26, letterSpacing: 1.1, fontWeight: "400", textAlign: "center", marginBottom: 10, paddingHorizontal: 30, }} > {Quote} </Text> <Text style={{ color: "black", fontSize: 30, textAlign: "right", fontWeight: "800", }} > " </Text> <Text style={{ textAlign: "right", fontWeight: "300", fontSize: 16, fontStyle: "italic", color: "#000", }} > -- {Author} </Text> <TouchableOpacity onPress={randomQuote} style={{ backgroundColor: "black", padding: 20, borderRadius: 30, marginVertical: 20, }} > <Text style={{ color: "#fff", fontSize: 18, textAlign: "center" }}> {isLoading ? "Loading..." : "New Quote"} </Text> </TouchableOpacity> </View> </View> ); }; export default App;
关键修改点
在处理响应的then回调中,新增了const quoteData = result[0];,通过索引获取数组中的第一个引用对象,之后再访问quoteData.content和quoteData.author就能正确拿到对应的值。
内容的提问来源于stack exchange,提问作者Harshit Sharma
相关产品推荐
相关产品推荐

