首页 > 解决方案 > React Hook React.useEffect 错误

问题描述

React Hook React.useEffect 缺少依赖项:'params.id'。要么包含它,要么移除依赖数组 react-hooks/exhaustive-deps。我项目中的很多地方都出现了这个错误。

图像样本

import React, { Fragment } from "react";
import ArticleDetails from "./List";
import { connect } from "react-redux";
import {
  articleFetchById,
  articleFetch,
  articleFetchByChannel
} from "../../../redux/action/articles";

const Article = ({
  articles,
  articleFetchById,
  match: { params },
  auth,
  articleFetch,
  articleFetchByChannel
}) => {
  React.useEffect(() => {
    articleFetchById(params.id);
  }, [articleFetchById]);
  React.useEffect(() => {
    articleFetch();
  }, [articleFetch]);
  React.useEffect(() => {
    articleFetchByChannel();
  }, [articleFetchByChannel]);
  return (
    <Fragment>
      <ArticleDetails articles={articles} auth={auth} matchId={params.id} />
    </Fragment>
  );
};
const mapStateToProps = state => {
  return {
    articles: state.articles,
    auth: state.auth
  };
};
export default connect(mapStateToProps, {
  articleFetchById,
  articleFetch,
  articleFetchByChannel
})(Article);

标签: reactjsreact-hooksreact-functional-component

解决方案


您需要params.id在 useEffect 的第二个参数数组中传递(因为您在 useEffect 中使用它)。那应该可以解决警告。

React.useEffect(() => {
    articleFetchById(params.id);
  }, [articleFetchById, params.id]);

推荐阅读