【问题标题】:What are the conditions for react to re-renderreact 重新渲染的条件是什么
【发布时间】:2020-05-02 17:58:50
【问题描述】:

我不确定 react 什么时候会重新渲染。我没有任何性能问题,我现在也没有尝试优化性能。 我只是对 react 何时重新渲染感到好奇。

据我所知,react 会在运行 useEffect 之前绘制所有内容,并且在 useEffect 运行之后它会再次绘制。 这意味着它应该调用一次 NewLobby 的 return,然后调用一次 useEffect,然后再调用一次 NewLobby,导致日志:

hello
rerun
hello

当我点击刷新按钮时也应该如此。

但实际行为有所不同 => 页面第一次加载控制台打印时:

hello
hello
hello
rerun
hello

刷新按钮按预期工作。为什么还有 2 次重绘?

我的组件

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

const NewLobby = () => {
  const initialStateFactory = () => {
    return {
      loading: false,
      error: false,
      lobbies: 'Loading ...',
    };
  };

  const [lobbies, setLobbies] = useState(initialStateFactory());
  const [refresh, setRefresh] = useState(0);

  useEffect(() => {
    (async () => {
      const fetchLobbies = async () => {
        const result = await (
          await fetch(`${BACKEND_URL}/play/lobbies`, {
            method: 'POST',
            credentials: 'include',
          })
        ).json();
        return result;
      };
      const lobbies = await fetchLobbies();
      console.log('rerun');
      setLobbies(s => {
        return { ...s, lobbies };
      });
    })();
  }, [refresh]);

  return (
    <>
      <div>{console.log('hello')}</div>
      <button onClick={() => setRefresh(s => s + 1)}>Refresh</button>
    </>
  );
};

export default NewLobby;

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    对于这类问题,我通常建议使用Why did you render?。试一试,几乎可以保证指出您的问题。

    【讨论】:

      猜你喜欢
      • 2021-06-07
      • 2018-07-19
      • 1970-01-01
      • 2023-02-20
      • 1970-01-01
      • 2020-08-14
      • 1970-01-01
      • 1970-01-01
      • 2020-06-01
      相关资源
      最近更新 更多