简体   繁体   English

在功能反应组件中无限重新渲染

[英]Infinite re-render in functional react component

I am trying to set the state of a variable "workspace", but when I console log the data I get an infinite loop.我正在尝试设置变量“工作区”的 state,但是当我控制台记录数据时,我得到一个无限循环。 I am calling the axios "get" function inside of useEffect(), and console logging outside of this loop, so I don't know what is triggering all the re-renders.我在 useEffect() 内部调用 axios“get”function,并在此循环之外进行控制台日志记录,所以我不知道是什么触发了所有重新渲染。 I have not found an answer to my specific problem in this question .我没有在这个问题中找到我的具体问题的答案。 Here's my code:这是我的代码:

function WorkspaceDynamic({ match }) {
  const [proposals, setProposals] = useState([{}]);
  useEffect(() => {
    getItems();
  });

  const getItems = async () => {
    const proposalsList = await axios.get(
      "http://localhost:5000/api/proposals"
    );
    setProposals(proposalsList.data);
  };

  const [workspace, setWorkspace] = useState({});
  function findWorkspace() {
    proposals.map((workspace) => {
      if (workspace._id === match.params.id) {
        setWorkspace(workspace);
      }
    });
  }

Does anyone see what might be causing the re-render?有没有人看到可能导致重新渲染的原因? Thanks!谢谢!

The effect hook runs every render cycle, and one without a dependency array will execute its callback every render cycle.效果挂钩在每个渲染周期运行,没有依赖数组的挂钩将在每个渲染周期执行其回调。 If the effect callback updates state, ie proposals , then another render cycle is enqueued, thus creating render looping.如果效果回调更新 state,即proposals ,则另一个渲染周期被排队,从而创建渲染循环。

If you want to only run effect once when the component mounts then use an empty dependency array.如果你只想在组件挂载时运行一次效果,那么使用一个空的依赖数组。

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

If you want it to only run at certain time, like if the match param updates, then include a dependency in the array.如果您希望它仅在特定时间运行,例如匹配参数更新,则在数组中包含一个依赖项。

useEffect(() => {
  getItems();
}, [match]);

your use of useEffect is not correct.您对 useEffect 的使用不正确。 if your dependency array is empty it gets called every time any state data changes.as a result your useEffect is called which causes setProposals then it again causes useEffect to run and so on如果您的依赖项数组为空,则每次 state 数据更改时都会调用它。因此,您的useEffect会被调用,这会导致setProposals ,然后它会再次导致useEffect运行,依此类推

try this试试这个

useEffect(() => {
    getItems();
  } , []);   // an empty array means it will be called once only

I think it's the following: useEffect should have a second param [] to make sure it's executed only once.我认为是这样的: useEffect应该有第二个参数[]以确保它只执行一次。 that is:那是:

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

otherwise setProposal will modify the state which will trigger a re-render, which will call useEffect , which will make the async call, which will setProposal , ...否则setProposal将修改 state 这将触发重新渲染,这将调用useEffect ,这将进行异步调用,这将setProposal ,......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM