简体   繁体   中英

Axios Uncaught TypeError: Cannot read property 'map' of undefined

I'm trying to display data from my API in a React App with Axios.

I've created a simple method that connects to the REST API.

import axios from 'axios';
const API_URL = 'http://127.0.0.1:8888';

export default class ReviewAPI{
    getQuestions(title) {
        const url = `${API_URL}/api/questions/?title=${title}`;
        return axios.get(url).then(response => response.data);
    }
}

When I make the API call it returns back the response but as a Promise.

在此处输入图像描述

When I try to map through the response I get `cannot read property map of undefined'

export default function Questions({ response, setData, formData}) {
return (
    <Card className="m-3">
        <Card.Header>{response.description}</Card.Header>
        <Card.Body>
            { response.questions.map((question, idx) => {
                switch (question.type) {
                    case "text": return <FormText key={idx} question={question} setData={setData} formData={formData}/>;
                    case "textarea": return <FormTextArea key={idx} question={question} setData={setData} formData={formData}/>;
                    case "radio": return <RadioGroup key={idx} question={question} setData={setData} formData={formData}/>;
                    case "multiselect": return <MultiSelect key={idx} question={question} setData={setData} formData={formData}/>;
                    default: return [];
                }
            })}
        </Card.Body>
    </Card>
);

}

rewrite it like so:

getQuestions(title) {
            const url = `${API_URL}/api/questions/?title=${title}`;
            let data;
             axios.get(url).then(response => {data = response.data});
           return data
        }

when you call the reviewAPI.getQuestions(), all you will get is the data returned;

You need to await the promise before you can map over the items.

In a functional component you need to do this:

const questions = () => {
  const [questions, setQuestions] = useState([]);

  useEffect(async () => {
       const res= await reviewAPI.getQuestions();

       setQuestions(res.data);
   }, []);

   return 
      <Questions 
         response={questions} 
         setData={setData} 
         formData={formData}/>
}

Look for the code in your Axios interceptor

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM