首页 > 解决方案 > 反应钩子以获取响应标头

问题描述

我正在尝试从我的项目中的 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?

标签: reactjs

解决方案


我自己真的想通了。如果其他人遇到此问题,这是更新的代码:

  const [postCount, setPostCount] = useState();
  useEffect(() => {
    fetch(`${state.source.api}wp/v2/posts`).then((response) => {
      setPostCount(response.headers.get("X-WP-Total"));
    });
  }, []);
  console.log(postCount);

推荐阅读