ReactJS重新渲染太多。 React限制了渲染次数以防止无限循环

时间:2020-04-24 08:54:10

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

我很困。 这是代码;

 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);”上给出此错误; enter image description here

它还说DestinationRightBar发生错误

enter image description here

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

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);
}

目标对象的值为 enter image description here

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

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

1 个答案:

答案 0 :(得分:1)

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

请花几个小时来学习useEffect的工作原理。

Official Docs以获取useEffect。

Dan Abramov's complete guide about useEffect

我相信您应该在useEffect中使用destinationUrl作为依赖项。 这意味着在destinationUrl更改时调用api。

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