【问题标题】:Too many re-renders with React Hooks使用 React Hooks 重新渲染的次数过多
【发布时间】:2020-02-23 07:48:44
【问题描述】:

有人问过类似的问题,但我还没有找到针对这个特定问题的解决方案。我有一个组件可以渲染所有板,并且我正在使用自定义 useFetch 挂钩来获取所有板。

const BoardsDashboard = () => {

  let [boards, setBoards] = useState([]);

  const { response } = useFetch(routes.BOARDS_INDEX_URL, {});

  setBoards(response);

  return (
    <main className="dashboard">
      <section className="board-group">
        <header>
          <div className="board-section-logo">
            <span className="person-logo"></span>
          </div>
          <h2>Personal Boards</h2>
        </header>

        <ul className="dashboard-board-tiles">
          {boards.map(board => (
            <BoardTile title={board.title} id={board.id} key={board.id} />
          ))}
          <CreateBoardTile />
        </ul>
    
      </section>
    </main>
  );
};

const useFetch = (url, options) => {
  const [response, setResponse] = useState([]);
  const [error, setError] = useState(null);
  useEffect(() => {
    const fetchData = async () => {
      try {
        const res = await fetch(url, options);
        const json = await res.json();
        setResponse(json);
      } catch (error) {
        setError(error);
      }
    };
    fetchData();
  }, []);
  return { response, error };
};

由于setBoards(response) 行,我得到了太多的重新渲染。处理这个问题的正确方法是什么?

谢谢!

【问题讨论】:

    标签: reactjs fetch react-hooks


    【解决方案1】:

    听起来你可能想要一个 useEffect 钩子在响应更新时采取行动。

    useEffect(() => {
      setBoards(response);
    }, [response]);
    

    注意:如果您不需要更改 boards 状态,那么它可能根本不需要有状态,您可以使用 useFetch 挂钩的返回值并完成它.

    const { response: boards } = useFetch(...);
    

    【讨论】:

    • 谢谢!这行得通。你能告诉我这是怎么工作的,但是当我试图这样做时:`useEffect(() => { async () => { const { response } = await useFetch(routes.BOARDS_INDEX_URL, {}); setBoards( response); } }, []) ``` 我遇到了无效使用钩子错误?
    • 钩子必须在顶层,不能嵌套在其他钩子中。我的解决方案有效的原因是只有在响应发生变化时才会运行效果。由于响应仅在您最初的 useFetch 执行时发生变化,因此效果只会在那一次有趣。
    • 你的解决方案是被认为是“黑客”,还是应该使用正确的 React 代码?再次感谢您
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-07
    • 1970-01-01
    • 2021-09-09
    • 2020-03-28
    相关资源
    最近更新 更多