【问题标题】:Unhandled Rejection (TypeError): respo.json is not a function未处理的拒绝(TypeError):response.json 不是函数
【发布时间】:2020-11-16 12:15:37
【问题描述】:

我是 React 的初学者,遇到了一些问题。遇到问题 Unhandled Rejection (TypeError):respo.json 不是函数。

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;

【问题讨论】:

  • 你能给你的respo对象截图吗?
  • 应该是 respo.data 而不是 resp.json()

标签: javascript reactjs async-await axios use-effect


【解决方案1】:

使用 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() {
  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;

工作代码:https://codesandbox.io/s/elated-platform-1itbi?file=/src/App.js

【讨论】:

  • 现在我收到错误,因为 setMonster 不是函数。请找到上面的截图
【解决方案2】:

你的代码有两个问题:

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

这应该是:

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

这应该是:

const resp = respo.data;

respo.data 不是一个承诺,而是已经是 api 的结果。

注意:

要更新monster,您必须调用setMonster(resp) 而不是setMonster({ monster: resp })

【讨论】:

【解决方案3】:

使用 get/then 代替 async/await 怎么样?

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

【讨论】:

    猜你喜欢
    • 2018-12-09
    • 2021-10-14
    • 2020-05-06
    • 2019-10-27
    • 2020-09-26
    • 2021-04-16
    • 2021-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多