嗨,我是 react 和 react-query 的初學者。
下面的代碼,它作業正常!!
const { data, isLoading, isError, error } = useQuery("comments", () => {
return fetchComments(post.id);
});
它不作業。
const { data, isLoading, isError, error } = useQuery("comments", fetchComments(post.id))
這些有什么區別?
uj5u.com熱心網友回復:
在第一種情況下,您提供了一個將fetchComments作為回呼函式呼叫的函式。react-query 將獲取該函式并呼叫它,它將呼叫fetchComments
在第二種情況下,您正在立即運行 fetchComments 函式并將回傳值作為引數傳遞,并且 react-query 正在嘗試運行fetchComments將回傳的任何內容,我認為這是 Promise 而不是函式
在某些特定情況下,您可以只傳遞函式參考而不呼叫它,但您將無法傳遞任何道具:
const { data, isLoading, isError, error } = useQuery("comments", fetchAllComments)
您的第一個解決方案是正確的。
和建議,你可以使用箭頭函式而不回傳,對我來說它更具可讀性
const { data, isLoading, isError, error } = useQuery("comments", () => fetchComments(post.id));
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/507565.html
標籤:javascript 反应 反应查询
