react-router-domを最新バージョンにしてみましょう、みたいな記事がありましが、こちらはいかがでしょうか。
Reactで画面切り替えを行いたいが、検証ツールで見たところエラーになってしまう問題を解消したい
Warning: 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.
Uncaught TypeError: Cannot read properties of null (reading 'useRef')
at Object.useRef (react.development.js:1630:1)
at BrowserRouter (index.tsx:772:1)
at renderWithHooks (react-dom.development.js:16305:1)
at mountIndeterminateComponent (react-dom.development.js:20074:1)
at beginWork (react-dom.development.js:21587:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1)
at invokeGuardedCallback (react-dom.development.js:4277:1)
at beginWork$1 (react-dom.development.js:27451:1)
at performUnitOfWork (react-dom.development.js:26557:1)
Warning: 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.
Uncaught TypeError: Cannot read properties of null (reading 'useRef')
at Object.useRef (react.development.js:1630:1)
at BrowserRouter (index.tsx:772:1)
at renderWithHooks (react-dom.development.js:16305:1)
at mountIndeterminateComponent (react-dom.development.js:20074:1)
at beginWork (react-dom.development.js:21587:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1)
at invokeGuardedCallback (react-dom.development.js:4277:1)
at beginWork$1 (react-dom.development.js:27451:1)
at performUnitOfWork (react-dom.development.js:26557:1)
The above error occurred in the <BrowserRouter> component:
at BrowserRouter (http://localhost:3000/static/js/bundle.js:70782:5)
at App
Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.
Uncaught TypeError: Cannot read properties of null (reading 'useRef')
at Object.useRef (react.development.js:1630:1)
at BrowserRouter (index.tsx:772:1)
at renderWithHooks (react-dom.development.js:16305:1)
at mountIndeterminateComponent (react-dom.development.js:20074:1)
at beginWork (react-dom.development.js:21587:1)
at beginWork$1 (react-dom.development.js:27426:1)
at performUnitOfWork (react-dom.development.js:26557:1)
at workLoopSync (react-dom.development.js:26466:1)
at renderRootSync (react-dom.development.js:26434:1)
at recoverFromConcurrentError (react-dom.development.js:25850:1)
NameError (uninitialized constant World)
import './App.css';
import Header from './Header';
import Main from './Main';
import Proggramming from './Proggramming'
import Sns from './Sns'
import Touhou from './Touhou'
import { BrowserRouter, Link, Routes, Route } from "react-router-dom";
function App() {
return (
<>
<div>dd </div>
<BrowserRouter>
<div id='main'>
<Link to='/'>Home</Link>
<br />
<Link to='/Proggramming'>Proggramming</Link>
<br />
<Link to='/Sns'>Page2</Link>
<br />
<Link to='/Touhou'>Page3</Link>
<br />
<Header />
<Routes>
<Route exact path='/' element={<Main />}>
<Main />
</Route>
<Route path='/proggramming' element={<Proggramming />}>
<Proggramming />
</Route>
<Route path='/sns' element={<Sns />}>
<Sns />
</Route>
<Route path='/touhou' element={<Touhou />}>
<Touhou />
</Route>
</Routes>
</div>
</BrowserRouter>
</>
);
}
export default App;
useRefやフックスでなにか問題が起きたとエラーを解釈したのですが、私はこれらの機能を使った覚えがないです。そのため調べてもよくわからず、皆さんのお力添えをお願いした次第です。
お時間があれば宜しくお願い致しますm(_ _)m
react-router-domを最新バージョンにしてみましょう、みたいな記事がありましが、こちらはいかがでしょうか。
@starMagichat
Questioner回答ありがとうございます。
PowerShellにてこのような形でコマンドを打ちましたが、
もうすでに最新verになっていました。
PS C:\Users\starmagichat> npm react-router-dom -v
10.2.4
PS C:\Users\starmagichat> npm update react-router-dom
up to date, audited 9 packages in 756ms
found 0 vulnerabilities
PS C:\Users\starmagichat> npm react-router-dom -v
10.2.4
PS C:\Users\starmagichat>
もし他に方法などがありましたら、教えて頂けると幸いです。
私もそちらの
https://stackoverflow.com/questions/72383919/uncaught-typeerror-cannot-read-properties-of-null-reading-useref
という記事をもう少し確認してみますね
react-router-domの最新は6.23.0のようですが…?
一度アンインストールして、
react-router-dom@latest
をインストールしてみてはどうでしょう?
@starMagichat
Questionerたしかにverがちょっとおかしいですね。
なのでこのようなコマンドを実行してみました。
PS C:\Users\starmagichat> npm uninstall react-router-dom
removed 8 packages, and audited 1 package in 332ms
found 0 vulnerabilities
PS C:\Users\starmagichat> npm install react-router-dom@latest
added 8 packages, and audited 9 packages in 1s
found 0 vulnerabilities
PS C:\Users\starmagichat> npm react-router-dom -v
10.2.4
このようにやはり10.2.4になってしまいます
一応キャッシュのクリア等も試してみましたが、結果は同じでした
PS C:\Users\starmagichat> npm cache clean
npm ERR! As of npm@5, the npm cache self-heals from corruption issues
npm ERR! by treating integrity mismatches as cache misses. As a result,
npm ERR! data extracted from the cache is guaranteed to be valid. If you
npm ERR! want to make sure everything is consistent, use `npm cache verify`
npm ERR! instead. Deleting the cache can only make npm go slower, and is
npm ERR! not likely to correct any problems you may be encountering!
npm ERR!
npm ERR! On the other hand, if you're debugging an issue with the installer,
npm ERR! or race conditions that depend on the timing of writing to an empty
npm ERR! cache, you can use `npm install --cache /tmp/empty-cache` to use a
npm ERR! temporary cache instead of nuking the actual one.
npm ERR!
npm ERR! If you're sure you want to delete the entire cache, rerun this command
npm ERR! with --force.
npm ERR! A complete log of this run can be found in: C:\Users\starmagichat\AppData\Local\npm-cache\_logs\2024-04-27T09_27_22_128Z-debug-0.log
PS C:\Users\starmagichat> npm install react-router-dom@latest
up to date, audited 9 packages in 727ms
found 0 vulnerabilities
PS C:\Users\starmagichat> npm react-router-dom -v
10.2.4
PS C:\Users\starmagichat>
キャッシュクリアでエラーが発生しているようですね。
どうやらコマンドが変わっているようです。
@starMagichat
Questionerそうなのですね、ありがとうございます。キャッシュのクリアを試してみて、その後再度、アンインストール、インストールを行ってみました。
PS C:\Users\starmagichat> npm cache verify
Cache verified and compressed (~\AppData\Local\npm-cache\_cacache)
Content verified: 3438 (386976687 bytes)
Content garbage-collected: 612 (479515827 bytes)
Index entries: 3438
Finished in 13.341s
PS C:\Users\starmagichat>
PS C:\Users\starmagichat> npm uninstall react-router-dom
removed 8 packages, and audited 1 package in 308ms
found 0 vulnerabilities
PS C:\Users\starmagichat> npm react-router-dom -v
10.2.4
PS C:\Users\starmagichat> npm uninstall react-router-dom@latest
up to date, audited 1 package in 292ms
found 0 vulnerabilities
PS C:\Users\starmagichat> npm react-router-dom@latest -v
10.2.4
PS C:\Users\starmagichat> npm install react-router-dom@latest
added 8 packages, and audited 9 packages in 1s
found 0 vulnerabilities
PS C:\Users\starmagichat> npm -v
10.2.4
PS C:\Users\starmagichat>
ここで気になるのが、npm -vとnpm react-router-dom@latest -vが全く同じ出力結果なのです。
react-router-domの最新6.23.0をダウンロードできていなかったかと思いまして。
なるほど、そういうことでしたか。
npm view react-router-dom version
もしくは、
npm ls
これで確認できると思います。
npm -v
は引数に関係なく、npmのバージョンを返すだけのオプションらしいです。
@starMagichat
Questionerありがとうございます。おかげさまで、ver確認を行えました。
PS C:\Users\starmagichat> npm view react-router-dom version
6.23.0
一応最新verにはなっているみたいです。
※上記のバージョン関連のやり取りを手元で行わずの投稿となります。悪しからずご了承ください。
私の経験上の意見になって申し訳ないですが、<BrowserRouter>
の中で<Link>
を用いたことはありません。ネスト外に出されてみてはいかがでしょうか?
function App() {
return (
<>
<div>dd </div>
+ <Link to='/'>Home</Link>
+ <br />
+ <Link to='/Proggramming'>Proggramming</Link>
+ <br />
+ <Link to='/Sns'>Page2</Link>
+ <br />
+ <Link to='/Touhou'>Page3</Link>
+ <br />
+ <Header />
<BrowserRouter>
<div id='main'>
- <Link to='/'>Home</Link>
- <br />
- <Link to='/Proggramming'>Proggramming</Link>
- <br />
- <Link to='/Sns'>Page2</Link>
- <br />
- <Link to='/Touhou'>Page3</Link>
- <br />
- <Header />
<Routes>
// 以下略
少しでも参考になりますと幸いです。
助け舟、ありがとうございます!
@starMagichat
Questionerありがとうございます。
アドバイスを基にこのように修正してみました。
import './App.css';
import Header from './Header';
import Main from './Main';
import Proggramming from './Proggramming'
import Sns from './Sns'
import Touhou from './Touhou'
import { BrowserRouter, Link, Routes, Route } from "react-router-dom";
function App() {
return (
<>
<div>dd </div>
<Link to='/'>Home</Link>
<br />
<Link to='/Proggramming'>Proggramming</Link>
<br />
<Link to='/Sns'>Page2</Link>
<br />
<Link to='/Touhou'>Page3</Link>
<br />
<Header />
<BrowserRouter>
<div id='main'>
<Routes>
<Route exact path='/' element={<Main />}>
<Main />
</Route>
<Route path='/proggramming' element={<Proggramming />}>
<Proggramming />
</Route>
<Route path='/sns' element={<Sns />}>
<Sns />
</Route>
<Route path='/touhou' element={<Touhou />}>
<Touhou />
</Route>
</Routes>
</div>
</BrowserRouter>
</>
);
}
export default App;
この結果ですが、別のエラーが発生してしまい、真っ白な画面となっております。
エラーの内容は今から貼っていきますね。
@starMagichat
Questioner他のファイルとの相関関係が分からないので、現状提供いただいているコードから気づいた点のみ挙げさせていただきます。
<Route exact path='/' element={<Main />}>
exact
を初めて見まして、調べるとこれはv5の仕様だそうです(すでにご存じなら恐れ入りますが、React Router
はv5→v6で破壊的な変更が行われています)参照情報:https://zenn.dev/tomohide0102/articles/c4cae8a667ab80
おそらく関係ないとは思いますが、私はApp
ではなくmain.tsx/jsx
にルーティングを記述しています。
先に述べたように他のファイルとの相関関係が不明なので、取り急ぎ私が備忘録代わりにしているReact Router
の設定例を投稿いたします(これが解決の糸口になってくれれば幸いなのですが)
import { BrowserRouter, Routes, Route } from "react-router-dom";
︙
︙
{/* router / App 関連のコンポーネント */}
<BrowserRouter>
<Routes>
/* index パスコンポーネント(TOPページ)*/
<Route path='/' index element={<App />} />
/* 2 階層目のコンポーネント(サブページ類)*/
<Route path="archive-hoge" element={<MainHoge children={
<>children の内容</>
} />} />
<Route path="hogeSinglesComponents" element={<HogeSingles />}>
/* element が「指定されていないこと」によって警告エラーが表示されるため <Route index /> の記述は無し */
/* サブページの子ページのパス名:hogeSinglesComponents/single-XXXX */
<Route path="single-Foo" element={<HogeFoo />} />
<Route path="single-Piyo" element={<HogePiyo />} />
<Route path="single-John" element={<HogeJohn />} />
<Route path="single-Potie" element={<HogePotie />} />
<Route path="single-Carie" element={<HogeCarie />} />
<Route path="single-Gory" element={<HogeGory />} />
</Route>
/* 各種 2 階層目のコンポーネント(サブページ類)*/
<Route path="archive-service" element={<MainService />} />
<Route path="archive-staff" element={<MainStaff />} />
<Route path="archive-other" element={<MainOther />} />
<Route path="about" element={<MainAbout />} />
<Route path="contact" element={<MainContact />} />
/* すべての Route コンポーネントの path 値による設定を評価した上で「ベストマッチのものが選択される仕組み」なので、パスエントリーの最後に * を置く */
<Route path="*" element={<NotFound />} />
</Routes>
</BrowserRouter>
{/* router / App 関連のコンポーネント */}
上記コード及び以下の注釈は、私がReact router(v6)
を使用してきた経験とこの書籍の情報からまとめたものになります。
1:ルーティングパスのマッチングは switch-case文のような排他的マッチングではなく すべてのRouteコンポーネントのpath値による設定を評価した上で「ベストマッチのものが選択」 される。
2:<Routes>
の中で<Route>
は入れ子にできて、すべてのパスは相対的になる。
注意事項としてトップルートでのインデックスのパスは/だが(index には index 属性とルートコンポーネント(element={<App />
})、ルートパス(path='/')を指定)。
<Route path='/' index element={<App />} />
それ以外は頭に/を付けてはならない。2 階層目でもそのルートのパスは空文字にしないといけない。うっかり/about
とか書かない。
3:パスの記述で気をつけたほうがいい点
◎ 末尾に/をつけても無視される
◎ 一般的なglobや正規表現は使えない
◎ ワイルドカード*のみ使用可だが、記述できるのは末尾のみ
◎ 大文字・小文字を区別したい場合はRouteコンポーネントに caseSensitive属性を指定する
4:<Outlet>
について
子ルート要素のコンポーネントをレンダリングするために用意しておくプレースホルダー的なコンポーネントが<Outlet>
。パスがネスト元Routeのパス名だった場合は<Outlet />
には何もレンダリングされないので、それを避けるなら子ルートにインデックスパスでリダイレクト(例:<Route path="*" element={<Navigate to="/" replace />} />
)させるなり、Not Foundページを表示させる(当該 Route 階層の【パスエントリーの最後に*を置く】 例:<Route path="*" element={<PostNotFound />} />
)なりする必要がある。
または、その他の方法としてネストする場合は<Route index />
に elementが指定されていない場合は記述不要(=Outletの index は無し)。elementが「指定されていないこと」によって警告エラーが表示されるため。
5:サブディレクトリ指定の場合はパスに記述する(例:ドメインまたはサブドメイン/サブディレクトリ/path-string)
ルート直下に dist ファイルの中身を置く場合はパスはルート始点(topページの場合:'/')(ページ指定の場合:'/directory/PageComponent')でOK.
長くなりましたし、個人用備忘録の情報なので申し訳ないですが、お役に立てると嬉しいです。
@starMagichat
Questionerいえいえ、詳しく教えて頂けてとても嬉しいです。
React Routerのバージョンアップの件確認してみましたが、かなり文法変わっているのですね..
React Routerの設定例も自分なりに落とし込んで書いてみますね、
本当にありがとうございます。