当您打开页面时,React 应用程序会在循环中调用请求

React app calls a request in a loop when you open a page

我正在使用基于 React 构建的 Strapi。我有一个自定义页面,我试图显示一些数据。但是,当我打开该页面时,终端上的网络选项卡和调试器显示请求是在循环中触发的。由于我是 React 的新手,我不确定问题出在哪里,但我猜是 state.

  const { pathType, id } = useParams();
  const [data, setData] = useState([]);
  const getData = () => request(`/${pathType}/${id}`, {method: 'GET'});
 
  useEffect(() => {
    getData().then(response => {
      return response;
    }).then(setData).catch(e => console.log(e));
  });

  return (
    <>
      <Container className="container-fluid">
        <div className="row">
          {JSON.stringify(data, null, 2)}
        </div>
      </Container>
    </>
  );

这里是调试器的一部分,其中显示了来自 getData()

的请求
[2020-08-31T10:33:30.644Z] debug OPTIONS /hostings/40 (1 ms) 204
[2020-08-31T10:33:30.942Z] debug GET /hostings/40 (297 ms) 200
[2020-08-31T10:33:30.949Z] debug OPTIONS /hostings/40 (0 ms) 204
[2020-08-31T10:33:31.241Z] debug GET /hostings/40 (291 ms) 200
....

指的是在 useEffect

上做出反应 documentation

Data fetching, setting up a subscription, and manually changing the DOM in React components are all examples of side effects.

简单地说:在您的情况下,每次您通过使用 setData

更改 DOM 时,都会调用 useEffect

现在您希望 useEffect 仅在 data 为空时才 setData。为此,您应该向 useEffect 添加一个条件,如下所示:

useEffect(() => {
  if (data.lenght !== 0) return
  getData().then(response => {
    return response;
  }).then(setData).catch(e => console.log(e));
});

这将确保您仅在 data 为空时 setData


你可以查看Why effects run on each update

以及“引用 React 文档”

If you want to run an effect and clean it up only once (on mount and unmount), you can pass an empty array ([]) as a second argument.

所以useEffect应该看起来像

useEffect(() => {
  ...
}, []);