php - 为什么 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。
解决方案
我非常相信这里的错误是因为错误使用了async/await和promise
使用 Promise 时要记住的事项
- 每当你使用
synchronous
或时使用 Promiseblocking code
。 - 确保为所有的 Promise 编写
.catch
和.then
方法。 - 如果在一切使用后要做某事
.finally
- Promise 对象中所有方法的返回类型,无论是静态方法还是原型方法,再次都是一个
Promise.
使用 Async/Await 时要记住的事项
- 异步函数返回一个承诺。
- 异步函数使用隐式 Promise 来返回结果。即使您没有
promise
显式返回 a,该async
函数也会确保您的代码通过 Promise 传递。 await
阻塞函数内的代码执行async
,其中await statement
的一部分。await
语句可以在一个async
函数中重载
推荐阅读
- math - 寻找二维平面的隐式表示
- python - @pytest 个人测试装饰器即使在失败后也能继续断言?
- html - 用于基于电子的应用程序的类似 Wiki 的表格排序
- r - 在R中,找到给定特定列的相邻行
- java - 如何缩放我的 Android Studio 屏幕以适应模拟器?
- arduino - 不再检测到 Arduino Micro(对不起,我是菜鸟)
- javascript - addEventListener 'click' 只工作一次
- ti-nspire - 如何在 ti-nspire cas(线性方程组)中得到正确表达的答案(仅用常数表示)
- python - 如何添加浮动属性
- raspberry-pi4 - 如何让多个观众看到同一个 Tigervnc 虚拟屏幕