症状
useHistoryを使用して、その動作確認で、ハンドラの動作させた際に下記エラーが発生してしまいました。翻訳すると、
「キャッチされないエラー:無効なフック呼び出し。フックは、関数コンポーネントの本体の内部でのみ呼び出すことができます。これは、次のいずれかの理由で発生する可能性があります。」
1.2.3で記載されているいずれかの内容が原因でエラーが発生しているようです。
エラー
react-dom.development.js:14906 Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
at Object.throwInvalidHookError (react-dom.development.js:14906)
at useContext (react.development.js:1504)
at useHistory (hooks.js:18)
at SubmitHandle (fuga.jsx:40)
at HTMLUnknownElement.callCallback (react-dom.development.js:3945)
at Object.invokeGuardedCallbackDev (react-dom.development.js:3994)
at invokeGuardedCallback (react-dom.development.js:4056)
at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:4070)
at executeDispatch (react-dom.development.js:8243)
at processDispatchQueueItemsInOrder (react-dom.development.js:8275)
at processDispatchQueue (react-dom.development.js:8288)
at dispatchEventsForPlugins (react-dom.development.js:8299)
at react-dom.development.js:8508
at batchedEventUpdates$1 (react-dom.development.js:22396)
at batchedEventUpdates (react-dom.development.js:3745)
at dispatchEventForPluginEventSystem (react-dom.development.js:8507)
at attemptToDispatchEvent (react-dom.development.js:6005)
at dispatchEvent (react-dom.development.js:5924)
at unstable_runWithPriority (scheduler.development.js:468)
at runWithPriority$1 (react-dom.development.js:11276)
at discreteUpdates$1 (react-dom.development.js:22413)
at discreteUpdates (react-dom.development.js:3756)
at dispatchDiscreteEvent (react-dom.development.js:5889)
下記がソースになります。
fugaCreate.js
import React from "react";
import {useHistory} from "react-router-dom"
export const FugaCreate = () => {
function SubmitHandle() {
const history = useHistory()
history .push("/hoge")
}
return(
<button onClick={SubmitHandle}>ボタン</button>
)
}
解決策
useHistoryの宣言をトップレベルに移動させることで、解決しました。Reactのhookを使うとき、トップレベルにhookの宣言をしていないと、トップレベルで宣言したhookの数と、動作させたときのhookが異なっているため、上記エラーが発生してしまうようです。
fugaCreate.js
export const FugaCreate = () => {
const history = useHistory()
function SubmitHandle() {
history .push("/hoge")
}
return(
<button onClick={SubmitHandle}>ボタン</button>
)
}