Javascript 什么是修复react应用程序中此“无效挂钩调用”错误的正确方法?

Javascript 什么是修复react应用程序中此“无效挂钩调用”错误的正确方法?,javascript,reactjs,firebase,react-hooks,Javascript,Reactjs,Firebase,React Hooks,嗯,我有这个错误 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().c

嗯,我有这个错误

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>

删除了一些无关紧要的代码

钩子只能在呈现组件时调用,因此它们需要位于组件主体中

export const DataInput = () => {
  const firestore = useFirestore();
  const Post = (testTitle, testText) => {
    firestore.collection('schedule-data').doc('test').set({
      testTitle: testTitle,
      testText: testText
    })
  }
  // etc
}

不要在循环、条件或嵌套函数中调用钩子。相反,总是在React函数的顶层使用钩子。通过遵循此规则,可以确保每次呈现组件时都以相同的顺序调用挂钩。这就是允许React在多个useState和useEffect调用之间正确保留挂钩状态的原因。如果您感到好奇,可以使用解释

根据您的代码示例,我可以建议testTitle、testText以某种方式在DataInput中可用,因此您可以使用useCallback创建onClick处理程序。React将创建回调以用作处理程序,并且仅在testTitle、testText发生更改时重新创建

从“react”导入{useCallback}; 导出常量数据输入==>{ const makePost=useCallback=>{ 使用FireStore.collection'schedule-data'。文档'test'。设置{ testTitle:testTitle, testText:testText } },[testTitle,testText]; 回来 发布数据
}您正在函数中使用useFirestore,请稍后再试。非常感谢。