質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.46%
React.js

Reactは、アプリケーションのインターフェースを構築するためのオープンソースJavaScriptライブラリです。

Q&A

0回答

514閲覧

React hooksでエラーが出てしまう

2_34_koki

総合スコア67

React.js

Reactは、アプリケーションのインターフェースを構築するためのオープンソースJavaScriptライブラリです。

0グッド

0クリップ

投稿2020/11/17 09:29

やろうとしてること

webpackを使ってReact アプリケーションを動かしたい.

発生している問題

react-router-domを使ったルーティング処理中の中でReact.Lazyを使うと下記のエラーが発生する.

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:
import React from "react"; import { Route, RouteProps, Switch, BrowserRouter } from "react-router-dom"; type RouteDef = RouteProps & { key: string }; const routeDefs: RouteDef[] = [ { key: "home", path: "*", component: React.lazy(() => import("./page/Home")), }, ]; const withRouteComponent = (Comp: RouteProps["component"], props: any) => { if (!Comp) { throw new Error("Route Component not Defined"); } const RouteComponent = () => <Comp {...props} />; return RouteComponent; }; const routeComponents = routeDefs.reduce<{ [key: string]: RouteDef["component"]; }>((pre, routeDef) => { pre[routeDef.key] = withRouteComponent(routeDef.component, routeDef); return pre; }, {}); export const AppRouter = () => { return ( <BrowserRouter> <React.Suspense fallback="...loading"> <Switch> {routeDefs.map((routeDef) => ( <Route exact key={routeDef.key} path={routeDef.path} component={routeComponents[routeDef.key]} /> ))} </Switch> </React.Suspense> </BrowserRouter> ); };

自分の見解

create-react-appを使った場合ではうまく行っていたのでおそらくwebpack中の何かが原因だと考える.
今回,HtmlWebpackPluginを使っているのでこいつが原因かなと思っている.

助けて欲しいこと

なぜこのようなことが発生していて,その解決策は何か?

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだ回答がついていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.46%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問