reactjs - 反应钩子以获取响应标头
问题描述
我正在尝试从我的项目中的 API 获取响应标头。我一直在使用以下格式来获取我所有的其他 JSON 数据:
const [myData, setMyData] = useState();
useEffect(() => {
fetch(`${state.source.api}wp/v2/posts`)
.then((response) => response.json())
.then((data) => {
setMyData(data);
});
}, []);
console.log(myData);
上面返回了我所有的 WP 帖子,我只是想更新它以获取包含 X-WP-Total 的标题。我在网上尝试了一些其他的例子,但没有运气。
有谁知道如何做到这一点 - 没有 Axios?
解决方案
我自己真的想通了。如果其他人遇到此问题,这是更新的代码:
const [postCount, setPostCount] = useState();
useEffect(() => {
fetch(`${state.source.api}wp/v2/posts`).then((response) => {
setPostCount(response.headers.get("X-WP-Total"));
});
}, []);
console.log(postCount);
推荐阅读
- ruby-on-rails - RMagick/Imagemagick 文本处理对 Heroku 来说太慢了
- arrays - 如何在数据中有数组的地方传递 curl 发布请求?
- angular - 订阅 observable 的问题
- api - 如何使用 github api v3 获取特定数量的用户?
- php - 使用 Laravel 5.7:如何从数组中获取 json 值名称?
- customization - React boostrap Table自定义单元不呈现
- amazon-web-services - 适用于 Powershell Core 的 AWS 工具中的过滤器语法问题
- javascript - 在 Angular 中使用 rxjs 进行双向数据绑定
- macros - 为什么我不能访问在宏中声明的变量,除非我传入变量的名称?
- javascript - 索引不存在 JavaScript?