未处理的拒绝(TypeError):respo.json 不是函数

我是 React 的初学者,遇到了一些问题。遇到问题 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;

http://img4.mukewang.com/639196080001961213600569.jpg

http://img.mukewang.com/639196130001d71c13400665.jpg

动漫人物
浏览 63回答 3
3回答

江户川乱折腾

使用 respo.data 代替:您的响应有一个您需要获取的数据密钥。import React, { useEffect } from 'react';import {useState} from 'react';import logo from './logo.svg';import './App.css';import axios from 'axios';function App() {&nbsp; const [monster,setMonster]=useState([]);&nbsp; useEffect(()=>{&nbsp; &nbsp; async function fetchData() {&nbsp; &nbsp; &nbsp;const respo=await axios.get('https://jsonplaceholder.typicode.com/users')&nbsp; &nbsp; &nbsp;const resp=await respo.data;&nbsp; &nbsp; &nbsp;setMonster({monster:[...respo]});&nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; fetchData();},[]);&nbsp; return (&nbsp; &nbsp; <div className="App">&nbsp; &nbsp; &nbsp; <p>{console.log(monster)}</p>&nbsp; &nbsp; </div>&nbsp; );}export default App;工作代码:https://codesandbox.io/s/elated-platform-1itbi?file =/src/App.js

九州编程

您的代码中有两个问题:const {monster,setMonster}=useState([]);这应该是:const&nbsp;[monster,setMonster]&nbsp;=&nbsp;useState([]);const resp = await respo.data;这应该是:const&nbsp;resp&nbsp;=&nbsp;respo.data;respo.data不是承诺,而是 api 的结果。笔记:要更新monster,您必须调用setMonster(resp)notsetMonster({ monster: resp })

暮色呼如

只使用 get/then 而不是 async/await 怎么样?useEffect(()=>{&nbsp; &nbsp; axios.get('https://jsonplaceholder.typicode.com/users')&nbsp; &nbsp; &nbsp; &nbsp; .then(response => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; setMonster({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; monster:[...response.data]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }},[monster]);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript