亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在反應應用程序中修復此“無效掛鉤呼叫”錯誤的正確方法是什么?

在反應應用程序中修復此“無效掛鉤呼叫”錯誤的正確方法是什么?

桃花長相依 2022-05-26 14:36:03
好吧,我有這個錯誤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>刪除了一些無關緊要的代碼
查看完整描述

3 回答

?
冉冉說

TA貢獻1877條經驗 獲得超1個贊

Hooks 只能在渲染組件時調用,因此它們需要位于組件的主體中。


export const DataInput = () => {

  const firestore = useFirestore();

  const Post = (testTitle, testText) => {

    firestore.collection('schedule-data').doc('test').set({

      testTitle: testTitle,

      testText: testText

    })

  }

  // etc

}


查看完整回答
反對 回復 2022-05-26
?
函數式編程

TA貢獻1807條經驗 獲得超9個贊

不要在循環、條件或嵌套函數中調用 Hook。相反,請始終在 React 函數的頂層使用 Hooks。通過遵循此規則,您可以確保每次渲染組件時都以相同的順序調用 Hook。這就是允許 React 在多個 useState 和 useEffect 調用之間正確保留 Hooks 狀態的原因。(如果你好奇,可以在這里找到解釋)



查看完整回答
反對 回復 2022-05-26
?
素胚勾勒不出你

TA貢獻1827條經驗 獲得超9個贊

根據您的代碼示例,我可能會建議testTitle, testText以DataInput某種方式提供,因此您可以使用useCallback. React 將創建回調以用作處理程序,并且僅在testTitle, testText更改時重新創建。


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>

    )

}


查看完整回答
反對 回復 2022-05-26
  • 3 回答
  • 0 關注
  • 112 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號