页面在递归循环中渲染时出现错误:重新渲染次数过多。

huangapple go评论68阅读模式
英文:

Page render in recursive loop throws Error: Too many re-renders

问题

I have page with few forms components as defined below, everything in front works fine, however if I look my console logs the function Fetchmovies is continuously being executed and throws

caught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

Even without error this is undesirable I don't want to make hundreds of calls to the API url. My requirement is just to call the Fetchmovies function once the page loads first time and update Autocomplete component with the returning array. But I am not sure, why my page is rendered recursively.

import React, { useState, useEffect } from 'react';

function GetMovies() {
  var [movies_list, setMovies_list] = useState([]);

  async function Fetchmovies() {

    try {
      const response = await fetch(url, {
        method: 'GET',
        headers: {
          'Accept': 'application/json',
          'authorization': 'token'
        },
      });
      const data = await response.json();
      setMovies_list(data);
      console.log(data);
    } catch (e) {
      console.log(e);
    }
  }

  useEffect(() => {
    Fetchmovies();
  }, []); // Empty dependency array to execute only once on component mount

  return (
    <Card>
      <Divider />
      <CardContent>
        <Autocomplete
          id='movies'
          name='movies'
          getOptionLabel={(movie) => movie.service_name}
          multiple
          options={movies_list}
          renderInput={(params) => <TextField {...params} label='Impacted movies:' />}
        />
      </CardContent>
    </Card>
  );
}
export default GetMovies;

Please make sure to import the necessary components like Card, Divider, CardContent, Autocomplete, and TextField, and define the url variable appropriately in your code.

英文:

I have page with few forms components as defined below, everything in front works fine, however if I look my console logs the function Fetchmovies is continuously being executed and throws

caught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

Even without error this is undesirable I don't want to make hundreds of calls to the API url. My requirment is just to call the Fetchmovies function once the page loads first time and update Autocomplete component with the returning array. ButI am not sure, why my page is rendered recursively.

import React, { useState } from &#39;react&#39;;

function GetMovies() {
  var [movies_list, setMovies_list] = useState([]);

  async function Fetchmovies() {

    try {
      movies_list = await fetch(url, {
        method: &#39;GET&#39;,
        headers: {
          &#39;Accept&#39;: &#39;application/json&#39;,
          &#39;authorization&#39;:&#39;token&#39;
        },
      }).then(response =&gt; movies_list = response.json());
      console.log(movies_list);
    } catch (e) {
      console.log(e);
    }
  }
  Fetchmovies().then(setMovies_list(movies_list));

  return (
    &lt;Card&gt;
      &lt;Divider /&gt;
      &lt;CardContent&gt;
            &lt;Autocomplete
              id=&#39;movies&#39;
              name=&#39;movies&#39;
              getOptionLabel={(movies_list) =&gt; movies_list.service_name}
              multiple
              options={movies_list}
              renderInput={(params) =&gt; &lt;TextField {...params} label=&#39;Impacted movies:&#39; /&gt;}
            /&gt;
      &lt;/CardContent&gt;
    &lt;/Card&gt;
  );

}
export default GetMovies;

答案1

得分: 1

你应该使用useEffect,但是你的fetch和状态使用存在一些错误。

在这里查看你可以采取的替代方法:

import React, { useEffect, useState } from 'react';

function GetMovies() {
  var [movies_list, setMovies_list] = useState([]);

  async function Fetchmovies() {
    try {
      const res = await fetch(url, {
        method: 'GET',
        headers: {
          'Accept': 'application/json',
          'authorization': 'token'
        },
      });
      const data = await res.json();
      setMovies_list(data);
    } catch (e) {
      console.log(e);
    }
  }

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

  return (
    <Card>
      <Divider />
      <CardContent>
        <Autocomplete
          id='movies'
          name='movies'
          getOptionLabel={(movies_list) => movies_list.service_name}
          multiple
          options={movies_list}
          renderInput={(params) => <TextField {...params} label='Impacted movies:' />}
        />
      </CardContent>
    </Card>
  );

}
export default GetMovies;

请注意,我已经将代码中的特殊字符转义为适当的中文字符。

英文:

You should use useEffect but there are some errors on your fetch and the use of state.

Check here what you can do instead:

import React, { useEffect, useState } from &#39;react&#39;;

function GetMovies() {
  var [movies_list, setMovies_list] = useState([]);

  async function Fetchmovies() {
    try {
      const res = await fetch(url, {
        method: &#39;GET&#39;,
        headers: {
          &#39;Accept&#39;: &#39;application/json&#39;,
          &#39;authorization&#39;:&#39;token&#39;
        },
      });
      const data = await res.json();
      setMovies_list(data);
    } catch (e) {
      console.log(e);
    }
  }

  useEffect(() =&gt; {
    Fetchmovies();
  }, [])

  return (
    &lt;Card&gt;
      &lt;Divider /&gt;
      &lt;CardContent&gt;
            &lt;Autocomplete
              id=&#39;movies&#39;
              name=&#39;movies&#39;
              getOptionLabel={(movies_list) =&gt; movies_list.service_name}
              multiple
              options={movies_list}
              renderInput={(params) =&gt; &lt;TextField {...params} label=&#39;Impacted movies:&#39; /&gt;}
            /&gt;
      &lt;/CardContent&gt;
    &lt;/Card&gt;
  );

}
export default GetMovies;

答案2

得分: 1

这行代码

useEffect(() => {
    Fetchmovies().then(setMovies_list(movies_list));
}, [])

更新状态... 导致组件重新加载... 从而再次调用 Fetchmovies 等等。

英文:

This line

Fetchmovies().then(setMovies_list(movies_list));

updates state ... which causes the component to reload .. which calls Fetchmovies again etc.

Wrap your Fetchmovies call un a useEffect hook.

useEffect(() =&gt; {
    Fetchmovies().then(setMovies_list(movies_list));
}, [])

huangapple
  • 本文由 发表于 2023年5月18日 08:49:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76277064.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定