首页 > 解决方案 > 如何阻止 useEffect 一遍又一遍地重复

问题描述

import { useState, useEffect } from 'react';
import axios from 'axios';

export const GetData = (url) => {
  const [data, setData] = useState([]);

  useEffect(() => {
    const getData = async () => {
      try {
        const response = await axios.get(url);
        setData(response.data);
      } catch (error) {
        console.error(error);
      }
    };
    getData();
    return () => {};
  }, [data]);

  return {
    data,
  };
};

我将上面的组件用于多个多个组件。我的问题是请求不断重复。我想阻止它重复。它应该重复的唯一时间是“数据”发生变化时。我尝试使用 axios 的取消令牌,但没有奏效。我还尝试使用间隔来停止它(也许我做错了。我不知道)。下面的代码显示了我正在使用 GetData 组件的组件之一。希望这会有所帮助。

import React from 'react';
import { Card, Table, Button } from 'react-bootstrap';

import { DeleteData, GetData } from '../../../api';
import { useGlobalContext } from '../../../context';

const SectionTable = ({ url }) => {
  const { setIsEdit, getId } = useGlobalContext();
  const { data } = GetData(url);

  return (
    <>
      <Card style={{ maxHeight: '500px', overflowY: 'scroll' }}>
        <Card.Body>
          <Table striped responsive hover>
            <thead>
              <th>Section Level</th>
              <th>Section Name</th>
              <th></th>
              <th></th>
            </thead>
            <tbody>
              {data.map((section) => {
                return (
                  <tr key={section.id}>
                    <td>{section.section_level}</td>
                    <td>{section.section_name}</td>
                    <td>
                      <Button
                        variant='warning'
                        onClick={() => {
                          getId(section.id);
                          setIsEdit(true);
                        }}>
                        Edit
                      </Button>
                    </td>
                    <td>
                      <Button
                        variant='danger'
                        onClick={() => DeleteData(section.id)}>
                        Delete
                      </Button>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </Table>
        </Card.Body>
      </Card>
    </>
  );
};

export default SectionTable;
```**strong text**

标签: reactjsaxiosrerender

解决方案


将数据列为依赖项意味着效果在每次由data. 而是依赖于 url:

  useEffect(() => {
    const getData = async () => {
      try {
        const response = await axios.get(url);
        setData(response.data);
      } catch (error) {
        console.error(error);
      }
    };
    getData();
    return () => {};
  }, [url]);

推荐阅读