【问题标题】:How to re-render the result of a custom hook when data loads如何在数据加载时重新呈现自定义挂钩的结果
【发布时间】:2021-12-09 13:45:10
【问题描述】:

我正在尝试渲染自定义挂钩产生的项目数。此自定义需要一些时间从数据库中获取数据并返回一个计数(即:任何大于或等于零的整数)。

我当前的设置是调用自定义挂钩并将该值推送到 useState 挂钩以显示当前的项目数。

但是,这不起作用。当前发生的情况是只返回自定义挂钩中的第一项,而不是更新的项。

// A React Component
// gamePlays holds the amount of items returned from the useLoadSpecficRecords hook.
// However, when data initially loads, the length is `0`, but when loading is finished, the length may increase. 
// This increased length is not represented in the gamePlays variable.
const gamePlays = useLoadSpecficRecords(today).games.length

// I want to set the initial value of selected to the number of game plays, but only 
// `0` is being returned
const [selected, setSelected] = useState({
  count: gamePlays,
})

// This useEffect hook and placed gamePlays as a dependency, but that did not update the value.
  useEffect(() => {
  }, [gamePlays])

这些是指示长度确实加载但未在 gamePlays 变量中更新的日志:

0
0
0
0
0
2
// useLoadSpecficRecords Hook

import { useState, useEffect } from 'react'
import { API, Auth } from 'aws-amplify'
import { listRecordGames } from '../graphql/queries'

// Centralizes modal control
const useLoadSpecficRecords = (date) => {
  const [loading, setLoading] = useState(true)
  const [games, setData] = useState([])

  useEffect(() => {
    fetchGames(date)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [date])

  const fetchGames = async (date) => {
    try {
      const formatedDate = await date


      let records = await API.graphql({
        query: listRecordGames,
        variables: {
          filter: {
            owner: { eq: username },
            createdAt: { contains: formatedDate },
          },
        },
      })

      const allGames = records.data.listRecordGames.items
      const filteredGames = allGames.map(({ name, players, winners }) => {
        return {
          gameName: name,
          players: players,
          winners: winners,
        }
      })

      setLoading(false)
      setData(filteredGames)
    } catch (err) {
      console.error(err)
    }
  }

  return { games, loading }
}

export default useLoadSpecficRecords

【问题讨论】:

  • 我可以看看你的钩子的实现吗?
  • @PouyaAtaei 我刚刚添加了实现

标签: reactjs use-effect use-state


【解决方案1】:

在自定义挂钩 useLoadSpecficRecordsuseEffect 中,将依赖关系列表从 date 更改为 games。这应该会重新触发 useEffect 并且您应该会看到更新的数据。

Here is the new implementation: 

import { useState, useEffect } from 'react';
import { API, Auth } from 'aws-amplify';
import { listRecordGames } from '../graphql/queries';

// Centralizes modal control
const useLoadSpecficRecords = (date) => {
  const [loading, setLoading] = useState(true);
  const [games, setData] = useState([]);

  useEffect(() => {
    fetchGames(date);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [games]); <-- dependency list updated!

  const fetchGames = async (date) => {
    try {
      const formatedDate = date;

      let records = await API.graphql({
        query: listRecordGames,
        variables: {
          filter: {
            owner: { eq: username },
            createdAt: { contains: formatedDate },
          },
        },
      });

      const allGames = records.data.listRecordGames.items;

      const filteredGames = allGames.map(({ name, players, winners }) => {
        return {
          gameName: name,
          players: players,
          winners: winners,
        };
      });

      setLoading(false);
      setData(filteredGames);
    } catch (err) {
      console.error(err);
    }
  };

  return { games, loading };
};

export default useLoadSpecficRecords;

我还删除了您在第 17 行 date 之前的不必要等待。

【讨论】:

    猜你喜欢
    • 2023-02-01
    • 2022-01-02
    • 2018-09-03
    • 2021-11-02
    • 2021-12-06
    • 2020-11-08
    • 1970-01-01
    • 2022-01-27
    • 2021-05-17
    相关资源
    最近更新 更多