使用 UseEffect 挂钩复制控制台日志

问题描述 投票:0回答:1

我有以下 js 文件,我试图将我通过邮递员发出的请求复制到 api url http://localhost:1777/api/test

我的目标是模拟该请求并将响应放在我可以在浏览器控制台中看到的对象内。

我的问题是浏览器控制台显示两个对象而不是一个(基本上是重复的)。这让我相信“console.log(simulatedResponse)”行运行了两次,但我无法修复问题以使其只运行一次。

我的js文件代码:

import React, { useEffect, useState } from 'react';
import { MyEditor } from '@Editor/my-editor';

function MedEditor() {
  const URL = 'http://keycloak:1901/auth/realms/myEditor/protocol/openid-connect/token';
  const [token, setToken] = useState(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const getToken = async () => {
      const params = new URLSearchParams();

      params.append('grant_type', 'client_credentials');
      params.append('client_id', 'myEditor_cli_client');
      params.append('client_secret', 'myEditor_cli_client_secret');

      const response = await fetch(URL, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: params,
      });

      const data = await response.json();
      setToken(data.access_token);
      setIsLoading(false);
    };
    getToken();
  }, []);

  useEffect(() => {
    if (token) {
      simulateApiRequest();
    }
  }, [token]);

  const simulateApiRequest = async () => {
    const postData = {
      data: {
        correlationId: 123,
        subjectId: "01",
        text: "test text"
      }
    };

    const response = await fetch('http://localhost:1777/api/test', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + token,
      },
      body: JSON.stringify(postData),
    });

    if (response.ok) {
      const simulatedResponse = await response.json();
      console.log(simulatedResponse); // Display the simulated response in the console
      // Now you can use the simulated response as needed
    } else {
      console.error('API request failed:', response.status, response.statusText);
    }
  };

  return (
    <div className="editor-container">
      {isLoading ? (
        <p>Loading...</p>
      ) : token ? (
        <MedNoteEditor tokenProvider={{ getToken: () => token }} />
      ) : (
        <p>No token available.</p>
      )}
    </div>
  );
}

export default MedEditor;

我尝试更改 useffect 功能,但到目前为止尚未成功。谁能帮我解决这个问题吗?

javascript reactjs react-hooks javascript-objects
1个回答
0
投票

在您的

if(response.ok){…}
循环中,您可能会执行请求两次,比您想要的多执行一次。您可以直接直接
console.log(response.json())
,而不是添加另一个变量,重新调用要发送的请求。

© www.soinside.com 2019 - 2024. All rights reserved.