好吧,我有个错误
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. 我尝试了很多不同的方法来解决这个问题,但我失败了。
这是我的密码
export const DataInput = () => {
const Post = (testTitle, testText) => {
useFirestore().collection('schedule-data').doc('test').set({
testTitle: testTitle,
testText: testText
})
}
return(
<Button
variant="primary"
onClick={()=> Post(testTitle, testText)}>
POST data
</Button>删除了一些不重要的代码
发布于 2020-03-23 06:45:09
只有在呈现组件时才能调用钩子,因此它们需要在组件的主体中。
export const DataInput = () => {
const firestore = useFirestore();
const Post = (testTitle, testText) => {
firestore.collection('schedule-data').doc('test').set({
testTitle: testTitle,
testText: testText
})
}
// etc
}发布于 2020-03-23 06:51:51
不要在循环、条件或嵌套函数中调用钩子。相反,总是在反应函数的顶层使用钩子。通过遵循此规则,您可以确保每次组件呈现时都以相同的顺序调用钩子。这就是允许React正确地保留多个useState和useEffect调用之间的钩子状态的原因。(如果你好奇的话,可以解释一下这里)
发布于 2020-03-23 07:08:07
根据您的代码samle,我可能建议testTitle, testText以某种方式在DataInput中可用,因此您可以使用useCallback创建onClick处理程序。React将创建回调以用作处理程序,并在更改时只重新创建。
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>
)
}
https://stackoverflow.com/questions/60808924
复制相似问题