繁体   English   中英

React Hook React.useEffect 缺少依赖项:“loadData”。 包含它或删除依赖项数组

[英]React Hook React.useEffect has a missing dependency: 'loadData'. Either include it or remove the dependency array

我在 React js React Hook React.useEffect 的以下组件中收到此警告缺少依赖项:'loadData'。 包括它或删除依赖项数组。 不知道是什么问题

const ManageCourses = (props) => {
  const [data, setData] = React.useState([]);
  const [loading, setLoading] = React.useState(false);

  React.useEffect(() => {
    loadData();
  }, [props.instructor]);

  const loadData = async () => {
    setLoading(true);
    await axios
      .get(
        "http://localhost:4000/api/instructorcourses/" +
          props.instructor.InstructorID
      )
      .then((res) => {
        setData(res.data);
        setLoading(false);
      });
  };

  return (
    <div>
      {console.log(props.instructor)}
      <Row>
        <Col span={19}></Col>
        <Col span={4}>{/*<AddBadge loadData={loadData} />*/}</Col>
        <Col span={1}></Col>
      </Row>
      <br />
      <table className="table table-striped table-sm table-bordered small">
        <thead>
          <tr>
            <th className="w-25">Badge Name</th>
            <th className="w-75">Badge Detail</th>
            <th>Action</th>
          </tr>
        </thead>
        {!loading && (
          <tbody>
            {data.map((data, index) => ({
              /*<SingleBadge data={data} key={index} loadData={loadData} />*/
            }))}
          </tbody>
        )}
      </table>
    </div>
  );
};

您可以实施 2 种可能的解决方案,一种是在useEffect中移动loadData function,但您将无法在 useEffect scope 之外访问此useEffect

React.useEffect(() => {
  const loadData = async () => {
    setLoading(true);
    await axios
      .get(
        "http://localhost:4000/api/instructorcourses/" +
          props.instructor.InstructorID
      )
      .then((res) => {
        setData(res.data);
        setLoading(false);
      });
    };

    loadData();
  }, [props.instructor]);

另一种是将loadData包装在useCallback中,并将其添加到useEffect的依赖项中:

const loadData = React.useCallback(async () => {
    setLoading(true);
    await axios
      .get(
        "http://localhost:4000/api/instructorcourses/" +
          props.instructor.InstructorID
      )
      .then((res) => {
        setData(res.data);
        setLoading(false);
      });
  }, [props.instructor]);
React.useEffect(() => {
    loadData();
  }, [loadData]);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM