gpt4 book ai didi

reactjs - useQueries 的启用选项

转载 作者:行者123 更新时间:2023-12-04 07:26:49 27 4
gpt4 key购买 nike

我正在尝试像这样使用 useQueries

function App({ users }) {
const userQueries = useQueries(
users.map(user => {
return {
queryKey: ['user', user.id],
queryFn: () => fetchUserById(user.id),
}
})
)
}
然而,users 变量是由 useQuery 提供的,并且最初返回 undefined。这导致错误无法读取未定义的映射。我想像 useQuery 一样添加 enabled,但我在文档中的任何地方都没有看到它。你可以用一个简单的 useQuery 来做到这一点:
// Get the user
const { data: user } = useQuery(['user', email], getUserByEmail)

const userId = user?.id

// Then get the user's projects
const { isIdle, data: projects } = useQuery(
['projects', userId],
getProjectsByUser,
{
// The query will not execute until the userId exists
enabled: !!userId,
}
)

// isIdle will be `true` until `enabled` is true and the query begins to fetch.
// It will then go to the `isLoading` stage and hopefully the `isSuccess` stage :)
基本上我想要
function App({ users }) {
const userQueries = useQueries(
users.map(user => {
return {
queryKey: ['user', user.id],
queryFn: () => fetchUserById(user.id),
enabled: !!users
}
})
)
}

最佳答案

如果没有用户,您可以回退到传递给 useQueries 的空数组:

function App({ users }) {
const userQueries = useQueries(
users?.map(user => {
return {
queryKey: ['user', user.id],
queryFn: () => fetchUserById(user.id),
}
}) ?? []
)
}

关于reactjs - useQueries 的启用选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68169676/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com