フック呼び出しが無効です。フックは関数コンポーネントの本体内でのみ呼び出すことができます。質問する

フック呼び出しが無効です。フックは関数コンポーネントの本体内でのみ呼び出すことができます。質問する

React を使用してテーブルにいくつかのレコードを表示したいのですが、次のエラーが発生しました:

無効なフック呼び出し。フックは関数コンポーネントの本体内でのみ呼び出すことができます。これは、次のいずれかの理由で発生する可能性があります。

  1. Reactとレンダラー(React DOMなど)のバージョンが一致していない可能性があります。
  2. フックのルールに違反している可能性があります
  3. 同じアプリ内に React のコピーが複数ある可能性があります。この問題をデバッグして修正する方法に関するヒントについては、こちらをご覧ください。
import React, { Component } from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Paper from '@material-ui/core/Paper';

const useStyles = makeStyles(theme => ({
  root: {
    width: '100%',
    marginTop: theme.spacing(3),
    overflowX: 'auto'
  },
  table: {
    minWidth: 650
  }
}));

class allowance extends Component {
  constructor() {
    super();
    this.state = {
      allowances: []
    };

  }

  componentWillMount() {
    fetch('http://127.0.0.1:8000/allowances')
      .then(data => {
        return data.json();
      })
      .then(data => {
        this.setState({
          allowances: data
        });
        console.log('allowance state', this.state.allowances);
      });
  }

  render() {
    const classes = useStyles();
    return (<Paper className={classes.root}>
        <Table className={classes.table}>
          <TableHead>
            <TableRow>
              <TableCell>Allow ID</TableCell>
              <TableCell align="right">Description</TableCell>
              <TableCell align="right">Allow Amount</TableCell>
              <TableCell align="right">AllowType</TableCell>
            </TableRow>
          </TableHead>
          <TableBody> {
            this.state.allowances.map(row => (<TableRow key={row.id}>
                <TableCell component="th" scope="row">{row.AllowID}</TableCell>
                <TableCell align="right">{row.AllowDesc}</TableCell>
                <TableCell align="right">{row.AllowAmt}</TableCell>
                <TableCell align="right">{row.AllowType}</TableCell>
              </TableRow>
            ))
          }
          </TableBody>
        </Table>
      </Paper>
    );
  }

}

export default allowance;

ベストアンサー1

npm linkを使って構築したローカルライブラリをインストールしたときにこの問題が発生しましたcra。答えを見つけましたここ文字通りにはこうなります。

この問題は、npm link または同等のものを使用した場合にも発生する可能性があります。その場合、バンドラーは 2 つの React を「認識」する可能性があります。1 つはアプリケーション フォルダーにあり、もう 1 つはライブラリ フォルダーにあります。「myapp」と「mylib」が兄弟フォルダーであると仮定すると、考えられる修正方法の 1 つは、「mylib」から「npm link ../myapp/node_modules/react」を実行することです。これにより、ライブラリはアプリケーションの React コピーを使用するようになります。

したがって、次のコマンドを実行します。npm link <path_to_local_library>/node_modules/reactたとえば、私の場合はnpm link ../../libraries/core/decipher/node_modules/reactプロジェクト ディレクトリから実行すると、問題は解決しました。

おすすめ記事