React项目中Axios GET请求返回空数组的异步问题解决方案咨询
Hey there! I see exactly what's causing that empty/undefined log and the related errors in your code. Let's break down the problem and fix it step by step.
What's Going Wrong?
Your console.log(questionList) is printing undefined because of how React's async rendering works:
- When your
Testcomponent first mounts,questionListstarts as an empty array[]. - The Axios request in
useEffectruns asynchronously—your component doesn't wait for it to finish before rendering. - So
MainTestgets passed an emptyquestionList, meaningquestionList[questionNum](which isquestionList[0]initially) isundefined. This gets passed toQuestion, and trying to accessquestionList.questionthrows an error because you're accessing a property fromundefined. - By the time the Axios request completes and updates
questionList, the initial render has already thrown an error, which can block the component from re-rendering correctly even with valid data.
Your attempts with delays and isLoading likely didn't work because you weren't properly guarding the rendering of child components until the data was fully ready.
The Fixes
Let's implement two key changes to resolve this:
1. Add a Loading State in the Parent Component
Update your Test.js to track when data is loading, and only render MainTest once the data is ready:
import React, { useState, useEffect } from "react"; import Tutorial from "../Tutorial"; import MainTest from "../MainTest"; import axios from "axios"; const Test = () => { const [count, setCount] = useState(0); const [questionNum, setQuestionNum] = useState(0); const [questionList, setQuestionList] = useState([]); const [isLoading, setIsLoading] = useState(true); // Add loading state useEffect(() => { axios.get("http://localhost:3001/get/question") .then((response) => { setQuestionList(response.data); }) .finally(() => { setIsLoading(false); // Mark loading as done regardless of success/failure }); }, []); const questionHandler = () => { setQuestionNum(questionNum + 1); setCount(count + 1); }; // Show loading state until data is ready if (isLoading) { return <div>Loading questions...</div>; // Replace with a spinner if you want! } // Add a check for empty question list if (!questionList.length) { return <div>No questions available!</div>; } return ( <div> <MainTest questionList={questionList} questionNum={questionNum} questionHandler={questionHandler} /> </div> ); }; export default Test;
2. Add Safeguards in Child Components (Optional but Recommended)
Even with the loading state, adding null checks in child components prevents unexpected errors. Update your Question.js:
import React from "react"; import Styled from "styled-components"; function Question({questionList}) { console.log(questionList); // Now this will only log valid data once it's ready // Return placeholder if questionList is undefined if (!questionList) { return null; } return ( <QuestionWrap> <i className="far fa-calendar-alt"></i> <h3> {questionList.question?.split('</br>').map((line, index) => { // Add key prop for proper React list rendering return(<React.Fragment key={index}>{line}<br/></React.Fragment>) })} </h3> </QuestionWrap> ); } export default Question; const QuestionWrap = Styled.div ` width: 100%; height: 55%; display: flex; align-items: center; justify-content: center; flex-direction: column; i{ color: #b56467; font-size: 2rem; margin-bottom: 2rem; } h3 { text-align: center; font-family: "UhBeeBEOJJI"; color: #3a1a00; font-size: 2.7rem; line-height: 3.4rem; } `;
Why This Works
- The
isLoadingstate ensuresMainTestand its children only render after the Axios request completes andquestionListhas valid data. - Optional chaining (
questionList.question?) and null checks prevent your code from trying to access properties onundefinedvalues, even if something unexpected happens with the data load.
Give these changes a try—your console.log should now print the actual question data instead of undefined, and the errors should disappear!
内容的提问来源于stack exchange,提问作者Adorevoy

