首页 > 解决方案 > 为什么 fetch POST 返回待处理的 API 调用在 React

问题描述

我正在尝试创建一个反应按钮来从服务器发布/检索数据。我已经发布并检索了,但问题是每当我发布时,如果我检查开发人员工具,它会显示等待 API 调用。如果我刷新页面,我会得到新数据。

这是我的帖子:

getId = async(reaction) => {

      let eSlug = this.state.slug;

      let data = {
          reactiond: reaction,
          eSlugd: eSlug
      }
      
        await fetch("http://localhost:9000/react/",
        {
            method: "post",
            headers: { 
              'Accept': 'application/json',
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        }).then(response => response.json())
          .then(data => {
            console.log(data)
          });
  }

我的反应渲染:

<div className="row">
            <div className="col-all">
              <button className="emoji-static">
                <span className="emoji-like">Like</span>
                <span className="emoji-container">
                  <span className="emoji cool zoom" onClick={this.getId.bind(null,"1")}>
                    <img className="svg" src="/img/svg/cool.svg" alt="Cool" />
                    <span className="counter">{this.state.coolReaction}</span>
                  </span>
                  <span className="emoji love zoom" onClick={this.getId.bind(null,"2")}>
                    <img className="svg" src="/img/svg/love.svg" alt="Love" />
                    <span className="counter">{this.state.loveReaction}</span>
                  </span>
                  <span className="emoji laugh zoom" onClick={this.getId.bind(null,"3")}>
                    <img className="svg" src="/img/svg/laugh.svg" alt="Laugh" />
                    <span className="counter">{this.state.laughReaction}</span>
                  </span>
                  <span className="emoji sad zoom" onClick={this.getId.bind(null,"4")}>
                    <img className="svg" src="/img/svg/sad.svg" alt="Sad" />
                    <span className="counter">{this.state.sadReaction}</span>
                  </span>
                  <span className="emoji zoom" onClick={this.getId.bind(null,"5")}>
                    <img className="svg" src="/img/svg/angry.svg" alt="Angry" />
                    <span className="counter">{this.state.angryReaction}</span>
                  </span>
                </span>
              </button>
            </div>
        </div>

我不明白为什么它卡在挂起状态,因此,我没有为 console.log 得到任何东西你能指出我正确的方向吗?我是 React 的一个完整的初学者,来自 PHP。

标签: phpreactjs

解决方案


我非常相信这里的错误是因为错误使用了async/awaitpromise

使用 Promise 时要记住的事项

  • 每当你使用synchronous或时使用 Promise blocking code
  • 确保为所有的 Promise 编写.catch.then方法。
  • 如果在一切使用后要做某事.finally
  • Promise 对象中所有方法的返回类型,无论是静态方法还是原型方法,再次都是一个Promise.

使用 Async/Await 时要记住的事项

  • 异步函数返回一个承诺。
  • 异步函数使用隐式 Promise 来返回结果。即使您没有promise显式返回 a,该async函数也会确保您的代码通过 Promise 传递。
  • await阻塞函数内的代码执行async,其中await statement的一部分。
  • await语句可以在一个async函数中重载

推荐阅读