简体   繁体   English

多个Axios GET来自不同组件的请求

[英]Multiple Axios GET requests from different components

I have 2 different components that render in main screen. 我有2个不同的组件在主屏幕中呈现。 Both have multiple axios.get requests to fill some data. 两者都有多个axios.get请求来填充一些数据。 But at first page load only the last component returns data and the first one is waiting for like 60 seconds to fill it's data. 但是在第一页加载时,只有最后一个组件返回数据,第一个组件等待60秒才能填充数据。 I don't know if it's React issue or my express server issue so here is the sample codes 我不知道它是React问题还是我的快速服务器问题,所以这里是示例代码

Main.JS Main.JS

class App extends Component {
  render() {
    return (
      <div>
        <ComponentA />
        <ComponentB />
      </div>
    );
  }
}

ComponentA.JS ComponentA.JS

 async componentDidMount() {
        const live = await axios.get('api link');
        const current = await axios.get('api link');
        this.setState({
            some states
        })
    }

ComponentB.JS ComponentB.JS

async componentDidMount() {
        const live = await axios.get('api link');
        this.setState({
            some states
        })
    }

express.js express.js

var express = require('express');
var app = express();
var sql = require('mssql');

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Credentials", "true");
    res.header("Access-Control-Allow-Headers", "Origin,Content-Type, Authorization, x-id, Content-Length, X-Requested-With");
    res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
    next();
});

var server = app.listen(8081, function () {
    var host = server.address().address
    var port = server.address().port
});

app.get('/api', function (req, res) {
    res.end(some values)
})

Personally I'd just chain axios calls with .then() 就个人而言,我只是用.then()链接axios调用

    axios.get('api link').then(data => {
    let live = data
    axios.get('api link2').then(data2 =>
    let current = data2
         })
    })

That's without diving into all of your components and lifecycle events..but might be helpful I hope. 这并没有深入到你的所有组件和生命周期事件......但我希望可能会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM