得到**错误:无效的挂钩调用。挂钩只能在功能组件的主体内部调用。 **

时间:2020-04-22 09:09:33

标签: reactjs react-native

我正在使用材质ui,并且当我使用菜单组件时遇到错误错误:无效的挂接调用。只能在函数组件的主体内部调用挂钩。我正在使用带有Axios API的material-ui框架进行反应。我正在使用带有Axios API的Material-ui框架进行响应。我正在使用带有Axios API的Material-ui框架

import React, { Component } from 'react'
import ApiService from "../../service/ApiService";
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 Button from '@material-ui/core/Button';
import CreateIcon from '@material-ui/icons/Create';
import DeleteIcon from '@material-ui/icons/Delete';
import Typography from '@material-ui/core/Typography';
import { Grid, FormGroup, FormControlLabel } from '@material-ui/core';
import Switch from '@material-ui/core/Switch';
class CategoryListUserComponent extends Component<any,any>{

    constructor(props: any){
        super(props)
        this.state = {
            users: [],
            message: null
        }
        this.deleteUser = this.deleteUser.bind(this);
        this.editUser = this.editUser.bind(this);
        this.addUser = this.addUser.bind(this);
        this.reloadUserList = this.reloadUserList.bind(this);
    }

    componentDidMount() {
        this.reloadUserList();
    }

    reloadUserList() {
        ApiService.fetchUsers()
            .then((res) => {
                this.setState({users: res.data})
            });
    }

    deleteUser(userId: any) {
        ApiService.deleteUser(userId)
           .then(res => {
               this.setState({message : 'User deleted successfully.'});
               this.setState({users: this.state.users.filter((user: { id: any; }) => user.id !== userId)});
           })
    }

    editUser(id: any) {
        window.localStorage.setItem("userId", id);
        this.props.history.push('/edit-user');
    }

    addUser() {
        window.localStorage.removeItem("userId");
        this.props.history.push('/add-user');
    }

    render() {
        const [checked, setChecked] = React.useState(false);

        const toggleChecked = () => {
          setChecked((prev) => !prev);
        };
        return (
            <Grid>
                                <Typography variant="h4" style={style}>User Details</Typography>
                <Button variant="contained" color="primary" onClick={() => this.addUser()}>
                    Add User
                </Button>
                <Grid  container   className="listContainer">
                <Table>
                    <TableHead>
                        <TableRow>
                            <TableCell>Id</TableCell>
                            <TableCell>Initiator</TableCell>
                            <TableCell align="left">Category</TableCell>
                            <TableCell align="left">Date</TableCell>
                            <TableCell align="left">Time</TableCell>
                            <TableCell align="left"></TableCell>
                            <TableCell align="left"></TableCell>
                            <TableCell align="left"></TableCell>
                        </TableRow>
                    </TableHead>
                    <TableBody>
                        {this.state.users && this.state.users.map((row: { id: {} | null | undefined; name: React.ReactNode; email: React.ReactNode; username: React.ReactNode; age: React.ReactNode; salary: React.ReactNode; }) => (
                            <TableRow>
                                <TableCell component="th" scope="row">
                                    {row.id}
                                </TableCell>
                                <TableCell align="left">{row.name}</TableCell>
                                <TableCell align="left">{row.username}</TableCell>
                                <TableCell align="left">13-10-2020</TableCell>
                                <TableCell align="left">10:00 AM</TableCell>
                                <TableCell align="left"><FormGroup>
                                    <FormControlLabel
                                        control={<Switch size="small" checked={checked} onChange={toggleChecked} />}
                                        label="Small"
                                    />
                                    <FormControlLabel
                                        control={<Switch checked={checked} onChange={toggleChecked} />}
                                        label="Normal"
                                    />
                                    </FormGroup>
                                    </TableCell>
                                <TableCell align="left" onClick={() => this.editUser(row.id)}><CreateIcon /></TableCell>
                                <TableCell align="left" onClick={() => this.deleteUser(row.id)}><DeleteIcon /></TableCell>

                            </TableRow>
                        ))}
                    </TableBody>
                </Table>

            </Grid>
            </Grid>
        );
    }

}

const style ={
    display: 'flex',
    justifyContent: 'center'
}

export default CategoryListUserComponent;

3 个答案:

答案 0 :(得分:1)

渲染功能的开头是:

render() {
    const [checked, setChecked] = React.useState(false);

但是您不能在此处使用useState,必须将checked变量移至组件状态(在构造函数中):

this.state = {
    users: [],
    message: null,
    checked: false
}

并重写toggleChecked函数:

toggleChecked = () => {
    this.setState({checked: !this.state.checked});
};

答案 1 :(得分:0)

您不得按照documentation“钩子在类内部不起作用”中所述使用钩子类组件

您可能想尝试一些解决方法,但不适用于每种用例:how-to-use-react-hooks-in-class-components

答案 2 :(得分:0)

如上所述

挂钩是React 16.8中的新增功能。 它们使您无需编写类即可使用状态和其他React功能。

因此,基本上,您可以编写一个类(不需要钩子),也可以编写带有钩子的功能组件。