【问题标题】:ReactJS Too many re-renders. React limits the number of renders to prevent an infinite loopReactJS 重新渲染太多。 React 限制渲染次数以防止无限循环
【发布时间】:2020-08-07 19:17:12
【问题描述】:

我太难了。 这是代码;

 const Destination = (props) => {
  const classes = useStyles();
  const destinationUrl = props.match.params.dest_url;
  const [destination, setDestination] = React.useState();

  useEffect(() => {
    if (!destination) {
      getDestinationByUrl(destinationUrl).then((destination) => {
        console.log("destination", destination); //result is attached below
        setDestination(destination);
      });
    }
  }, [destination]);

  return (
    <div className={classes.root}>
      <Grid container spacing={3} className={classes.mainGrid}>
        {destination && (
          <>
            <Grid item xs={12}>
              <Typography variant="h5" className="title">
                {destination.title}
              </Typography>
            </Grid>
            <DestinationRightBar destination={destination} />
          </>
        )}
      </Grid>
    </div>
  );
};

它在“setDestination(destination);”上给出了这个错误

它还说 DestinationRightBar 发生错误

如果我删除目标右栏,它会起作用! 什么是让它工作的正确方法!

getDestinationByUrl 是一个获取

export function getDestinationByUrl(url) {
  return fetch(baseUrl + url, {
    method: "GET",
    headers: {
      Accept: "application/json",
      "content-type": "application/json",
      Authorization: `Bearer ${TOKEN}`,
    },
  })
    .then((response) =>
      response.ok ? response.json().then(handleResponse) : handleNotOk(response)
    )
    .catch(handleError);
}

目标对象的值为

DestinationRightBar 只是另一个使用目标对象作为输入的组件。

export default function DestinationRightBar(props) {
  const { destination } = props;

【问题讨论】:

  • 可以加getDestinationByUrl代码吗?因为它真的很奇怪
  • 我加了,只是抓取
  • 当您使用setDestination 设置时,destination 的值是多少。
  • destination的值为json对象。
  • 我已经编辑了添加的对象

标签: reactjs react-hooks infinite-loop use-effect use-state


【解决方案1】:

您的useEffect 代码确实没有任何意义。使用该代码,您说当目标更改时,运行效果,但在您的效果中您有if (!destination),这意味着如果目标是虚假的,请调用 api,为什么? 更糟糕的是,您尝试更改效果内的目标值,这将导致无限循环。

请花几个小时了解useEffect 的工作原理。

Official Docs 用于使用效果。

Dan Abramov's complete guide about useEffect.

我相信你应该在 useEffect 中使用 destinationUrl 作为依赖。 这意味着当destinationUrl发生变化时调用api,这是有道理的。

  useEffect(() => {
    if (destinationUrl) {
      getDestinationByUrl(destinationUrl).then((destination) => {
        setDestination(destination);
      });
    }
  }, [destinationUrl]);

【讨论】:

  • 由于destinationUrl有值,如果我把它放在“if”语句中请求未发送。
  • @KubilayBayraktar 我更新了,它必须是 if (destinationUrl) 而不是 if (!destinationUrl)
  • @KubilayBayraktar 但这是否解决了React limits the number of renders to prevent an infinite loop 问题?
  • 我通过删除 DestinationRightBar 组件中的这段代码解决了这个问题:setTags(destination.tags.split(","));
  • @KubilayBayraktar 你提到了 2 个问题,其中一个是无限循环问题。如果不使用我的解决方案,删除该组件是否也解决了无限循环?
猜你喜欢
  • 1970-01-01
  • 2020-08-06
  • 2021-02-26
  • 1970-01-01
  • 1970-01-01
  • 2020-09-22
  • 2021-07-01
相关资源
最近更新 更多