我有一個物件陣列,我需要獲取一個屬性,但它回傳未定義并且不知道為什么。有誰知道如何解決?
const [questions, setQuestions] = useState({});
const [index, setIndex] = useState(0);
async function handleQuestions() {
const fetchQuestions = await fetchTriviaApi();
setQuestions(fetchQuestions.results);
}
useEffect(() => {
handleQuestions();
}, []);
回傳問題:
(5) [{…}, {…}, {…}, {…}, {…}]
0: {category: 'Entertainment: Music', type: 'boolean', difficulty: 'medium', question: 'Rapper Snoop Dogg's real name is 'Cordozar Calvin Broadus, Jr.'.', correct_answer: 'True', …}
1: {category: 'Entertainment: Video Games', type: 'multiple', difficulty: 'medium', question: 'Which of these "Worms" games featured 3D gameplay?', correct_answer: 'Worms 4: Mayhem', …}
2: {category: 'Vehicles', type: 'multiple', difficulty: 'easy', question: 'What UK Train does NOT go over 125MPH?', correct_answer: 'Sprinter', …}
3: {category: 'Entertainment: Video Games', type: 'boolean', difficulty: 'medium', question: 'Tony Hawk's Pro Skater was released in 1999.', correct_answer: 'True', …}
4: {category: 'Entertainment: Video Games', type: 'boolean', difficulty: 'hard', question: 'In The Witcher 3, the Zoltan Chivay Gwent card can be found under the Hanged Man's Tree.', correct_answer: 'True', …}
length: 5
回傳問題[索引]:
{category: 'Entertainment: Music', type: 'boolean', difficulty: 'medium', question: 'Rapper Snoop Dogg's real name is 'Cordozar Calvin Broadus, Jr.'.', correct_answer: 'True', …}
回傳問題[index].category: 當我嘗試訪問任何屬性時,它回傳未定義。
uj5u.com熱心網友回復:
您需要將questions狀態初始化為一個空陣列。
const [questions, setQuestions] = useState([]);
并且在訪問這些專案時,您必須檢查questionsAPI 呼叫是否填充了這些專案。
{questions.length > 0 && questions[index].category}
uj5u.com熱心網友回復:
很可能您的 fetch 沒有被正確等待。您還需要等待 json() 。請記住 setState 是異步的,而不是立即的。只有在下一次重新渲染時,您才能確保更改資料。
uj5u.com熱心網友回復:
也許是因為您將問題狀態初始化為一個物件,所以一旦解決了 handleQuestions,問題 [1] 確實是未定義的。
uj5u.com熱心網友回復:
我相信你應該映射物件陣列。
let results = questions.map(item => item.category)
希望這會有所幫助:https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/427167.html
標籤:javascript 反应
上一篇:使用字典映射物件陣列
