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

时间:2019-01-31 09:11:19

标签: javascript node.js reactjs express axios

我在主屏幕上呈现了2个不同的组件。两者都有多个axios.get请求来填充一些数据。但是在第一页加载时,只有最后一个组件返回数据,而第一个组件则等待大约60秒来填充其数据。我不知道这是React问题还是我的快递服务器问题,所以这是示例代码

Main.JS

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

ComponentA.JS

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

ComponentB.JS

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

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)
})

1 个答案:

答案 0 :(得分:1)

我个人只是将axios调用与.then()链接

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

这并没有涉及到所有组件和生命周期事件。.但我希望这会有所帮助。