3 回答

TA貢獻(xiàn)1877條經(jīng)驗(yàn) 獲得超1個(gè)贊
Hooks 只能在渲染組件時(shí)調(diào)用,因此它們需要位于組件的主體中。
export const DataInput = () => {
const firestore = useFirestore();
const Post = (testTitle, testText) => {
firestore.collection('schedule-data').doc('test').set({
testTitle: testTitle,
testText: testText
})
}
// etc
}

TA貢獻(xiàn)1807條經(jīng)驗(yàn) 獲得超9個(gè)贊
不要在循環(huán)、條件或嵌套函數(shù)中調(diào)用 Hook。相反,請(qǐng)始終在 React 函數(shù)的頂層使用 Hooks。通過(guò)遵循此規(guī)則,您可以確保每次渲染組件時(shí)都以相同的順序調(diào)用 Hook。這就是允許 React 在多個(gè) useState 和 useEffect 調(diào)用之間正確保留 Hooks 狀態(tài)的原因。(如果你好奇,可以在這里找到解釋)

TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超9個(gè)贊
根據(jù)您的代碼示例,我可能會(huì)建議testTitle, testText以DataInput某種方式提供,因此您可以使用useCallback. React 將創(chuàng)建回調(diào)以用作處理程序,并且僅在testTitle, testText更改時(shí)重新創(chuàng)建。
import {useCallback} from 'react';
export const DataInput = () => {
const makePost = useCallback(() => {
useFirestore().collection('schedule-data').doc('test').set({
testTitle: testTitle,
testText: testText
})
}, [testTitle, testText]);
return (
<Button
variant="primary"
onClick={makePost}
{/* Avoid inline callback declaration */}
>
POST data
</Button>
)
}
添加回答
舉報(bào)