繁体   English   中英

在React中使用Fetch从服务器获取数据

[英]Using Fetch in React to fetch data from server

我正在尝试使用以下代码从服务器(Node.js)获取数据:

componentDidMount = () => {
fetch('http://localhost:3000/numberofjobs')
.then(response => response.json())
.then(numberOfJobs => {
      console.log(numberOfJobs)
})
}

那是我在Node上的路线:

const handleNumberOfJobs = (req, res, Register) => {
 Register.find({})
  .then(users =>  {
  const total = users.reduce((sum, { numberOfJobs }) => sum + 
  numberOfJobs, 0);
  console.log(total);
  })
  .then(response => res.json(response))
}

我遇到的一个问题是前端console.log没有显示在控制台中,我也不知道为什么。 在服务器端,当页面加载时,它会进行console.log求和和所有操作,因此它可以正常工作,所以我相信我在React上做错了什么。 我想将此信息带到我的前端,以便可以在页面上显示它。

非常感谢!!

TL; DR

服务器端代码中如何使用箭头函数的隐式返回有一个错误。

解决方法是只增加一个return total; 在第一个.then(...)处理程序中。

细节

首先,让我们把它弄清楚:我同意关于不忽略错误检查的意见! (无论是fetch还是其他。)

无论如何:您可以在.then(...)处理程序中使用箭头函数。 但是第一个中的最后一个语句是console.log(total) 该调用的返回值是undefined ,它成为箭头函数的隐式返回值。 然后,promise将其作为第二个.then(...)处理程序中的response值传递。 (您可以通过在第二个.then(...)处理程序中添加console.log(response)进行验证。

解决方法是只增加一个return total; 在第一个.then(...)处理程序中:

const handleNumberOfJobs = (req, res, Register) => {
  Register
    .find({})
    .then(users => {
      const total = users.reduce(
        (sum, { numberOfJobs }) => sum + 
            numberOfJobs, 0
      );
      console.log(total);   // <-- returns undefined
      return total;         // <-- pass on to next promise
    })
    .then(response => {
      // console.log(response);  // if you're curious
      res.json(response)
    })
  }
}

个人提示:缩进/整理代码以简化维护。

暂无
暂无

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

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