React TypeScript:停止进行多个api调用的状态

时间:2019-09-09 10:46:06

标签: reactjs typescript react-hooks

页面加载后,我需要从URL获取值并将其发送到API,但是由于父对象的状态正在更改,因此api调用被进行了3次。我希望它只调用一次API。

import React, {useContext, useEffect} from 'react';
import Context from '../components/context';
import {RouteComponentProps} from 'react-router-dom';

interface MyProps {
  confirmationCode: string,
}

const Confirm: React.FC<RouteComponentProps<MyProps>> = (props) => {

  useEffect(() => {
    console.log('FIRE Just Once!!!')
  });

  const { global } = useContext(Context) as {global: any};
  const confirmationCode = props.match.params.confirmationCode;

  async function checkConfirmationCode() {
    const response = await fetch(`${global.apiUrl}/user/confirm_email`, {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({confirmationCode})
    });

    if (response.status === 200) {
      localStorage.setItem("warning", 'confirmed');
    } else if (response.status === 400) {
      localStorage.setItem("warning", 'invalid');
    }
  }

  if (confirmationCode) {
    checkConfirmationCode();
  }

  return (
    <div>test</div>
  );
} 

export default Confirm;

2 个答案:

答案 0 :(得分:2)

使用以下代码更新您的useEffect钩子:

useEffect(() => {
  if (confirmationCode) {
    checkConfirmationCode();
  }
}, [confirmationCode]);

答案 1 :(得分:-1)

使用此代码是一种解决方案。 useEffect(() => { console.log('FIRE Just Once!!!') }, [])

顺便说一句,如果您想拒绝多功能调用, 您可以在debounce中使用lodash来避免在特定时间段内调用多个函数。

import { debounce } from 'lodash';
...

const debouncedApiCall = debounce(checkConfirmationCode, 500);
// call `checkConfirmationCode` once in 500ms

...

if (confirmationCode) {
  debouncedApiCall();
}
...

REF:https://lodash.com/docs/4.17.15#debounce