You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React项目中Axios GET请求返回空数组的异步问题解决方案咨询

Fixing the Async Data Loading Issue in Your React Component

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:

  1. When your Test component first mounts, questionList starts as an empty array [].
  2. The Axios request in useEffect runs asynchronously—your component doesn't wait for it to finish before rendering.
  3. So MainTest gets passed an empty questionList, meaning questionList[questionNum] (which is questionList[0] initially) is undefined. This gets passed to Question, and trying to access questionList.question throws an error because you're accessing a property from undefined.
  4. 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;

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 isLoading state ensures MainTest and its children only render after the Axios request completes and questionList has valid data.
  • Optional chaining (questionList.question?) and null checks prevent your code from trying to access properties on undefined values, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 13:09:05