【问题标题】:Hooks can only be called inside the body of a function component. But it's already in a functionHooks 只能在函数组件的主体内部调用。但它已经在一个函数中
【发布时间】:2019-04-19 18:40:45
【问题描述】:

我正在关注这里的教程:http://adazzle.github.io/react-data-grid/docs/examples/column-sorting 并尝试实现 react-data-grid,因为它为我提供了进行排序、特定单元格的树状视图等功能。但我遇到了一个错误如下:

Invariant Violation:Hooks 只能在函数组件内部调用。

import React from "react";
import { useState } from "react";
import ReactDOM from "react-dom";
import ReactDataGrid from "react-data-grid";
import "./styles.css";

const defaultColumnProperties = {
    resizable: true,
    sortable: true,
    width: 300
};

const columns = [
    { key: "key1", name: "key1", sortDescendingFirst: true },
    { key: "key2", name: "key2" },
    { key: "key3", name: "key3" },
    { key: "key4", name: "key4" },
    { key: "key5", name: "key5" }
].map(c => ({ ...c, ...defaultColumnProperties }));

const sortRows = (initialRows, sortColumn, sortDirection) => rows => {
    const comparer = (a, b) => {
        if (sortDirection === "ASC") {
            return a[sortColumn] > b[sortColumn] ? 1 : -1;
        } else if (sortDirection === "DESC") {
            return a[sortColumn] < b[sortColumn] ? 1 : -1;
        }
    };
    return sortDirection === "NONE" ? initialRows : [...rows].sort(comparer);
};

class Example extends React.Component {
    constructor() {
        super();
        this.state = { data: [] };
    }

    async componentDidMount() {
        const url = "http://localhost:8080";
        try {
            const response = await fetch(url, {
                mode: "cors",
                method: "GET"
            });
            if (!response.ok) {
                throw Error(response);
            }
            const res = await response.json();

            this.setState({ data: res });
        } catch (error) {
            console.log(error);
        }
    }

    someStateFunction = data => {
        return useState(data);
    };

    render() {
        const [rows, setRows] = this.someStateFunction(
            this.state.data
        );
        return (
            <ReactDataGrid
                columns={columns}
                rowGetter={i => rows[i]}
                rowsCount={rows.length}
                minHeight={5000}
                onColumnResize={(idx, width) =>
                    console.log(`Column ${idx} has been resized to ${width}`)
                }
                onGridSort={(sortColumn, sortDirection) =>
                    setRows(
                        sortRows(
                            this.state.data,
                            sortColumn,
                            sortDirection
                        )
                    )
                }
            />
        );
    }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<Example />, rootElement);

我该如何解决? useState() 仅在函数内部使用?我做错了吗?

package.json 如下所示:

{
  "name": "dc-react-test-2",
  "version": "1.1.0",
  "description": "",
  "keywords": [],
  "main": "src/index.js",
  "dependencies": {
    "react": "^16.8.2",
    "react-dom": "^16.8.2",
    "react-scripts": "2.1.5",
    "react-bootstrap": "0.32.4",
    "react-data-grid": "5.0.1",
    "immutable": "3.8.2"
  },
  "devDependencies": {},
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  },
  "browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
  ]
}

请帮忙。我是一个反应非常新手。

【问题讨论】:

    标签: javascript reactjs create-react-app react-hooks react-data-grid


    【解决方案1】:

    Example 在您的示例中不是函数组件,而是类组件。函数组件只是一个常规的 javascript 函数。 Here is an article about the difference.

    您在这里混合了类组件状态和函数组件状态 (useState)。你必须选择。要么你坚持使用类组件,你必须向this.state添加一些状态来跟踪排序等,或者你去完整的功能,然后你获取in a useEffect hook

    【讨论】:

    • 你能指导我在我的代码中需要做哪些更改,以使用功能组件或类组件吗?在这里,我的要求是使用 async/await 进行 rest api 调用,并使用 useState(),如我的代码所示。
    猜你喜欢
    • 2020-06-17
    • 2021-09-12
    • 2019-04-14
    • 2020-04-06
    • 2020-04-21
    • 2020-06-22
    • 2019-09-07
    • 2019-11-01
    相关资源
    最近更新 更多