反应:useState回调/获取数据无限循环

时间:2019-07-31 19:37:39

标签: reactjs

如果运行下面的代码,则会遇到无限循环(如控制台日志中所示)。我认为发生这种情况是因为useState回调(setEvents)导致重新渲染,从而导致应用App重新运行,然后重新获取数据,再次调用useState回调,依此类推。该代码基于我在网上看到的众多示例-我在做什么错了?


services:
  integration_tests:
    image: ${serviceName}:tests
    environment:
      - INTEGRATION_TEST_URL=http://webapi:${servicePort}
    entrypoint: bash /wait_for_it.sh webapi:${servicePort} -t 0 --
    command: >
      bash -c "go test -v -run Integration ./... |tee /TestResults/IntegrationTestsTestResults.out 
      && go2xunit -input /TestResults/IntegrationTestsTestResults.out -output /TestResults/IntegrationTestsTestResults.xml"
    depends_on:
      - webapi
    volumes: 
      - ./TestResults:/TestResults
  webapi:
    image: ${serviceName}:${imageTag}
    environment:
      - API_PORT=${servicePort}
      - CORE_SERVICE_EVA_BASE_PATH=http://domain.abc.com:32250
    ports: 
      - ${servicePort}:${servicePort} 

1 个答案:

答案 0 :(得分:1)

将声明移到效果内,并传递一个空数组作为第二个参数:

console.log('Running App'); // DEBUG


useEffect(() => {

let basename = (window.location.hostname === 'localhost') ? '/' : '/event_monitor';
let apiURL = 'https://example-api.com';
const [events, setEvents] = useState(null);

async function fetchData(apiURL) {
    console.log('fetching data'); // DEBUG
    const response = await fetch(apiURL);
    const json = await response.json();
    setEvents(json);
}
    fetchData(apiURL)
}, []);