【问题标题】:My Network Response shows in the console but won't save to my variable我的网络响应显示在控制台中,但不会保存到我的变量中
【发布时间】:2020-04-08 23:01:36
【问题描述】:

我正在使用 React.js 和 Axios 在我的本地机器上调用 django api。当我发出请求并检查网络控制台时,数据就在那里。但是当我尝试将响应数据保存到变量并记录结果时,什么都没有显示。我曾尝试使用 jquery 并得到相同的结果。看来我也只能在使用'await'时在控制台中获取响应数据。

我的 Context-Provider.js 代码的一部分:

async componentDidMount() {
        var resp = await axios.get('http://localhost:8000/campaign/')
        .then((res) => {
        resp = res.data
        })
        console.log(resp)

        this.setState({
            campaigns: resp.data,

        })
    }

Here is my consoles output for the network Response

【问题讨论】:

    标签: reactjs django-rest-framework axios


    【解决方案1】:

    多想一下,将async/awaitthen 结合起来可能是个坏主意。我建议你选择一个或另一个

    axios.get('http://localhost:8000/campaign/')
    .then((res) => {
      this.setState({ campaigns: res.data })
    })
    

    const resp = await axios.get('http://localhost:8000/campaign/')
    this.setState({ campaigns: resp.data })
    

    【讨论】:

    • 我已将其更改为这个,但它似乎仍然无法正常工作。 async componentDidMount() { var resp = await axios.get('http://localhost:8000/campaign/') .then((res) => { return res.data }) console.log(resp) this.setState({ campaigns: resp, }) }
    • 在使用 console.log 测试后,我的 axios 调用似乎永远不会完成并进入下一行?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-28
    • 2020-01-05
    • 2020-05-28
    • 2015-03-14
    相关资源
    最近更新 更多