LoginSignup
4
0

More than 1 year has passed since last update.

reactでhooksを使っているコンポーネントの呼び出す時のエラー

Last updated at Posted at 2020-11-18

エラー内容

  • Warning: React has detected a change in the order of Hooks called by...
  • Error: Rendered more hooks than during the previous render.

原因1

エラーにあるように、前回のレンダリングに比べてHooksの数が異なる

例えば以下の場合、10回クリックするとHooksの数が1から2になってしまう

10回クリックするとエラーになる
function App() {
  const [count, setCount] = useState(0);
  if (count < 10)
    return (
      <button type="button" onClick={() => setCount((count) => count + 1)}>
        count is: {count}
      </button>
    );

  const [] = useState(); // ダミー
  return <div>You clicked more than 10 times !</div>;
}

Hooksは関数の初めに定義しておく

エラーにならない
function App() {
  const [count, setCount] = useState(0);
  const [] = useState();

  if (count < 10)
    return (
      <button type="button" onClick={() => setCount((count) => count + 1)}>
        count is: {count}
      </button>
    );
  return <div>You clicked more than 10 times !</div>;
}

原因2

関数形式でコンポーネントを呼んでいる

hooksは使えない
return SomeComponent(someProps)

ちゃんとcreateElementをするか、jsxで記述する

createElementを使う
import {createElement} from 'react';
...
return createElement(SomeComponent, someProps)
...
jsxを使う
import React from 'react';
...
return <SomeComponent {...someProps} />
...
4
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
4
0