简体   繁体   English

如何从前端react.js中的node.js从多个数据库中获取数据

[英]How to fetch data from multiple db from the node.js in frontend react.js

I have the below code, where I have to get data from all the files in the same DB. 我有以下代码,必须从同一数据库中的所有文件中获取数据。 Node.js is running at the backend. Node.js在后端运行。 When I try the below code, I always get the last fetch, can anyone please help me how to fix this. 当我尝试下面的代码时,我总是会得到最新的数据,任何人都可以帮助我解决此问题。 The below is from the react JS frontend. 以下是来自React JS前端的内容。

    componentDidMount() {
        console.log("This Worked Sucessfully")
        this.getDataFromDb();
        if (!this.state.intervalIsSet) {
          let interval = setInterval(this.getDataFromDb, 1000);
          this.setState({ intervalIsSet: interval });
        }
      }

      getDataFromDb = () => {fetch('http://172.24.78.202:3001/api/passed')
          .then(data => data.json())
          .then(res => this.setState({ passed: res.data }));
      };

      getDataFromDb = () => {fetch('http://172.24.78.202:3001/api/failed')
          .then(data => data.json())
          .then(res => this.setState({ failed: res.data }));
      };

      getDataFromDb = () => {fetch('http://172.24.78.202:3001/api/all')
          .then(data => data.json())
          .then(res => this.setState({ data2: res.data }));
      };
      render() {
        const primaryColor = getColor('primary');
        const secondaryColor = getColor('secondary');
        const { passed, failed, data2 } = this.state

From what I see by your code, you seem to be re-writing your goGetDataFromDB two times. 从您的代码来看,您似乎两次重写了goGetDataFromDB Try changing the names of each function or, the way you call them. 尝试更改每个函数的名称或调用它们的方式。 You can also take advantage of Promise.all to group the results of each call into a single return handle. 您还可以利用Promise.all将每个调用的结果分组到单个返回句柄中。

Check this link for the documentation of Promise.all 检查此链接以获取Promise.all的文档。

You could refactor your current code to something like this: 您可以将当前代码重构为如下形式:

class MyComponent extends React.Component {
  componentDidMount() {
    this.getDataFromDb();
    if (!this.state.intervalIsSet) {
      let interval = setInterval(this.getDataFromDb, 1000)
      this.setState({intervalIsSet: true })
    }
  }

  getDataFromDb = () => {
    Promise.all([
      'http://172.24.78.202:3001/api/passed',
      'http://172.24.78.202:3001/api/failed',
      'http://172.24.78.202:3001/api/all'
    ].map(url => (
      fetch(url)
        .then(data => data.json())
        .then(res => res.data)
      )
    )).then(([passed, failed, data2]) => 
      this.setState({ passed, failed, data2 })
    );
  }

  render() {
    //...
  }
}

I tried to keep as much as your code as possible so you could notice the differences. 我试图保留尽可能多的代码,以便您可以注意到它们之间的差异。

I hope this helps. 我希望这有帮助。

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

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