【发布时间】: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