如何解决useEffect中依赖项的问题?

时间:2020-03-13 13:56:38

标签: reactjs redux react-redux react-hooks

我需要发出一次请求,但是出现与依赖项有关的错误。如果我添加到依赖项,将会有一个无限循环。

在这种情况下,您建议做什么?

enter image description here

代码:

import React from "react";
import { useEffect } from "react";
import { useObjects } from "../../store/api";
import { connect } from "react-redux";
import { GetObjectsAC } from "../../store/ObjectRecucer";
import { Object } from "./Object";

let MapStateToProps = state => {
  return {
    currentObj: state.objReducer.CurrentObjects
  };
};
export let ObjectBlock = props => {
  const { request } = useObjects();
  useEffect(() => {
    const data = request("/api/objects").then(res => {
      props.GetObjectsAC(res.message);
    });
  }, []);
  const objBlock = props.currentObj.map((el, i) => (
    <Object key={i} street={el.street} home={el.home} />
  ));
  return <div>{objBlock}</div>;
};
export let ObjectContainer = connect(
  MapStateToProps,
  { GetObjectsAC }
)(ObjectBlock);

1 个答案:

答案 0 :(得分:0)

类似这样的情况将解决警告:

import React from "react";
import { useEffect } from "react";
import { useObjects } from "../../store/api";
import { connect } from "react-redux";
import { GetObjectsAC } from "../../store/ObjectRecucer";
import { Object } from "./Object";

let MapStateToProps = state => {
  return {
    currentObj: state.objReducer.CurrentObjects
  };
};
export let ObjectBlock = props => {
  const { request } = useObjects();
  const { GetObjectsAC, currentObj } = props; // destructure props
  useEffect(() => {
    const data = request("/api/objects").then(res => {
      GetObjectsAC(res.message);
    });
  }, [GetObjectsAC]); // Add value to deps array
  const objBlock = currentObj.map((el, i) => (
    <Object key={i} street={el.street} home={el.home} />
  ));
  return <div>{objBlock}</div>;
};
export let ObjectContainer = connect(
  MapStateToProps,
  { GetObjectsAC }
)(ObjectBlock);