简体   繁体   English

React:为什么它会跳过我的“获取”function?

[英]React: Why is it skipping over my “fetch” function?

I am a bit new to React and am trying to have data from MySQL print in my console, but it seems not to print what I want it to print.我对 React 有点陌生,我试图在我的控制台中打印来自 MySQL 的数据,但它似乎没有打印出我想要打印的内容。

 componentDidMount(){ console.log('Hi') fetch('http://localhost:6000/test').then((response) => response.json()).then((users) => console.log('This is your data')) console.log('Hi') }

Initially, I had ".then((users) => console.log('This is your data', users))", but because it didn't print out, I removed "users" to just test the string.最初,我有“.then((users) => console.log('This is your data', users))”,但因为它没有打印出来,所以我删除了“users”来测试字符串。

In my console, it prints Hi, a newline, and Hi again.在我的控制台中,它会再次打印 Hi、换行符和 Hi。 Because it shows this, I'm assuming it skips over my fetch statement as it doesn't print "This is your data" either.因为它显示了这一点,所以我假设它跳过了我的 fetch 语句,因为它也没有打印“这是你的数据”。 Am I thinking the right way?我的想法正确吗? Is there a reason "This is your data" doesn't print as well?是否有原因“这是您的数据”也无法打印? Thanks for the help in advance!我在这里先向您的帮助表示感谢!

It's isn't skipping over the fetch, this is just how asynchronous functions and Promises work in javascript.它并没有跳过 fetch,这就是异步函数和 Promise 在 javascript 中的工作方式。

fetch returns a promise and is asynchronous, so when execution is plowing through componentDidMount it does the first log, queues up the fetch (which resolves later), then does the second log. fetch返回一个 promise 并且是异步的,因此当执行通过componentDidMount时,它会执行第一个日志,将fetch排队(稍后解决),然后执行第二个日志。 You'll see the final "this is your data" log when the fetch promise chain resolves.fetch promise 链解析时,您将看到最终的“这是您的数据”日志。

If you want to really see the logs in order then you may want to use an async function.如果您想真正按顺序查看日志,则可能需要使用async function。

async componentDidMount(){
  console.log('Hi')
  await fetch('http://localhost:6000/test') // <-- pause execution and wait for promise to resolve before continuing
    .then((response) => response.json())
    .then((users) => console.log('This is your data'))
  console.log('Hi')
}

Check if the fetch was successful and handle rejected Promises检查 fetch 是否成功并处理被拒绝的 Promises

async componentDidMount(){
  console.log('Hi')
  await fetch('http://localhost:6000/test')
    .then((response) => {
      if (!response.ok) { // <-- check the ok status
        throw new Error('Response not ok');
      }
      return response.json();
    })
    .then((users) => console.log('This is your data'))
    .catch(err => console.error(err)); // <-- log thrown errors
  console.log('Hi')
}

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

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