【问题标题】:react axios no response反应axios没有反应
【发布时间】:2021-11-11 12:07:25
【问题描述】:

我在响应中调用我的 api 完全没有得到任何响应:

constructor(props) {
        super(props);
        this.state = {
            team: {}
        }
    }

    getData() {
        axios.get('http://game.test/api/characters')
            .then(response => this.setState({ team: response.data.characters }));
     }

    componentDidMount() {
        this.getData();
        console.log(this.state);
    }

状态是空的,如果我 console.log 在 .then 中的任何内容,控制台也是空的(就像代码的那部分不可访问)。 同样在“网络”选项卡上,一切似乎都很好(状态 200 和正确的数据)。

【问题讨论】:

  • async.. await?
  • 这能回答你的问题吗? Use Async/Await with Axios in React.js
  • 我们真的帮不上什么忙:你还没有向我们展示你是如何使用console.log的,我们也看不到 JSON 的结构是什么。
  • @YevgenGorbunkov — 在我看来,thisgetData 的使用很好。

标签: javascript reactjs


【解决方案1】:

setState 是异步的,因此 console.log(this.state) 将在 componentDidMount 中的 this.getData() 之前执行。如果您想记录获取结果/错误,请使用 async/await 将日志放入 getData:


constructor(props) {
        super(props);
        this.state = {
            team: {},
            error: ""
        }
    }

    getData = async () => {
        await axios.get('http://game.test/api/characters')
              .then(response => this.setState({ team: response.data.characters }))
              .catch(error =>  this.setState({error: error}))
        console.log(this.state)  //log fetch result/error 
          }

    componentDidMount() {
        this.getData();
        console.log(this.state)    //log init state 
    }

【讨论】:

    【解决方案2】:

    试试这个,它会起作用的

    App.js

    import Child from "./Comp/Chid";
    
    export default function App() {
      return (
        <div className="App">
          <Child />
          <h2>Start editing to see some magic happen!</h2>
        </div>
      );
    }
    

    Comp/Child.js

    import React from "react";
    import axios from "axios";
    
    class Child extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          team: {}
        };
      }
    
      async getData() {
        await axios
          .get("https://jsonplaceholder.typicode.com/posts")
          .then((response) => {
            console.log(response);
            this.setState({ team: response.data.characters });
          });
      }
    
      componentDidMount() {
        this.getData();
        console.log(this.state);
      }
    
      render() {
        return <div>Hello</div>;
      }
    }
    
    export default Child;
    

    【讨论】:

      【解决方案3】:

      我认为您的代码没有太大问题,如果有帮助,请尝试以下操作

      1. 在更新状态之前先尝试 console.log(response)
      2. 尝试 async getData () 并等待 axios,因为您正在获取异步操作

      【讨论】:

      • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-25
      • 1970-01-01
      • 1970-01-01
      • 2020-10-28
      • 2020-10-22
      • 2016-06-17
      相关资源
      最近更新 更多