LoginSignup
1
0

More than 1 year has passed since last update.

ReactのチュートリアルでcreateContextを追加したら保存毎にエラーが出た話

Posted at

react のチュートリアルでcreateContextを追加したら保存毎にエラーが出続け流ようになったけど、GPT先生に聞くとあっさり治った話
React: v18.2.0

エラー内容

Warning: You are calling ReactDOMClient.createRoot() on a container that has already been passed to createRoot() before. Instead, call root.render() on the existing root instead if you want to update it.
ReferenceError: Cannot access 'App' before initialization at main.tsx:21:10
[hmr] Failed to reload /src/App.tsx. This could be due to syntax errors or importing non-existent modules. (see errors above)

GPT先生

このエラーは、2つのソースが原因で発生している可能性があります。

1つ目のエラーに関連する Warning: You are calling ReactDOMClient.createRoot() on a container that has already been passed to createRoot() before. について

この警告は、Appを再レンダリングした場合に何度も毎回新しいルートを作成しようとしていることが原因であると言えます。そのため、次のように書くと良いです。

const rootElement = document.getElementById('root')
if (rootElement !== null && rootElement.childNodes.length === 0) {
  const root = ReactDOM.createRoot(rootElement);
  ...
}
...

最後に

ChatGPTが出てから学習に詰まることが少なくなって良き

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0