简体   繁体   中英

Unhandled Rejection (TypeError): respo.json is not a function

I'm a beginner in React and stuck with some problem. Getting an issue Unhandled Rejection (TypeError): respo.json is not a function.

import React, { useEffect } from "react";
import { useState } from "react";
import logo from "./logo.svg";
import "./App.css";
import axios from "axios";

function App() {
  const { monster, setMonster } = useState([]);

  useEffect(() => {
    async function fetchData() {
      const respo = await axios.get("https://jsonplaceholder.typicode.com/users");
      const resp = await respo.data;
      setMonster({ monster: [...resp] });
    }

    fetchData();
  }, [monster]);

  return (
    <div className="App">
      <p>{console.log(monster)}</p>
    </div>
  );
}

export default App;

在此处输入图像描述

在此处输入图像描述

在此处输入图像描述 Use respo.data instead:

Your response has a data key which you need to fetch.

import React, { useEffect } from 'react';
import {useState} from 'react';
import logo from './logo.svg';
import './App.css';
import axios from 'axios';

function App() {
  const [monster,setMonster]=useState([]);

  useEffect(()=>{
    async function fetchData() {
     const respo=await axios.get('https://jsonplaceholder.typicode.com/users')
     const resp=await respo.data;
     setMonster({monster:[...respo]});

    }

      fetchData();
},[]);
  return (
    <div className="App">
      <p>{console.log(monster)}</p>
    </div>
  );
}

export default App;

Working code:https://codesandbox.io/s/elated-platform-1itbi?file=/src/App.js

There are two problems in your code:

  1. const {monster,setMonster}=useState([]);

This should be:

const [monster,setMonster] = useState([]);
  1. const resp = await respo.data;

This should be:

const resp = respo.data;

respo.data is not a promise, but already the result of the api.

Note:

To update monster , you have to call setMonster(resp) not setMonster({ monster: resp })

How about just using get/then instead of async/await?

useEffect(()=>{
    axios.get('https://jsonplaceholder.typicode.com/users')
        .then(response => {
            setMonster({
                monster:[...response.data]
            });
        });
    }
},[monster]);

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