React Hook useEffect 缺少一个依赖项:'props'。包括它或删除依赖项数组。useEffect 中的 props 没有数据

Fia*_*jha 1 reactjs redux

我使用 axios 调用 api 方法以在 react hooks 组件中进行数据访问。我使用 react redux 进行状态管理。我从 useEffect 调用 fetchall 方法来获取所有课程。但是响应数组是空的并显示在上面的错误。状态或道具有问题。或者课程减速器不获取数据。这里是 api.js 的代码在行动。

import axios from "axios";

const baseUrl = "http://localhost:44306/api/"



export default {

    course(url = baseUrl + 'courses/') {
        return {
            fetchAll: () => axios.get(url),
            fetchById: id => axios.get(url + id),
            create: newRecord => axios.post(url, newRecord),
            update: (id, updateRecord) => axios.put(url + id, updateRecord),
            delete: id => axios.delete(url + id)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

课程组件有 2 个网格,第一个网格已被注释掉以关注问题。第二个网格有表格,应该在表格中显示课程。后端表有许多行已经用邮递员和数据库测试过。Courses.js 如下。

import React, { useState, useEffect } from "react";
import { connect } from "react-redux";
import * as actions from "../actions/course";
import { Grid, Paper, TableContainer, Table, TableHead, TableRow, TableCell, TableBody, withStyles, ButtonGroup, Button } from "@material-ui/core";
import CourseForm from "./CourseForm";
import EditIcon from "@material-ui/icons/Edit";
import DeleteIcon from "@material-ui/icons/Delete";
import { useToasts } from "react-toast-notifications";



const styles = theme => ({
    root: {
        "& .MuiTableCell-head": {
            fontSize: "1.25rem"
        }
    },
    paper: {
        margin: theme.spacing(2),
        padding: theme.spacing(2)
    }
})





const Courses = ({ classes, ...props }) => {
    const [currentId, setCurrentId] =useState(0)
    useEffect(() => {
        props.fetchAllCourses()    // here is error props is empty

    }, [])//componentDidMount

    //toast msg.
    const { addToast } = useToasts()

    const onDelete = id => {
        if (window.confirm('Are you sure to delete this record?'))
            props.deleteCourse(id,()=>addToast("Deleted successfully", { appearance: 'info' }))
    }





    return (
        <Paper className={classes.paper} elevation={3}>
            <Grid container>
                <Grid item xs={6}>

                    {/* <CourseForm {...({ currentId, setCurrentId })} /> */}
                </Grid>
                <Grid item xs={6}>
                    <TableContainer>
                        { <Table>
                            <TableHead className={classes.root}>
                                <TableRow>
                                    <TableCell>Title</TableCell>
                                    <TableCell>Details</TableCell>
                                    <TableCell>Category</TableCell>
                                    <TableCell></TableCell>
                                </TableRow>
                            </TableHead>
                            <TableBody>
                                {
                                    props.courseList.map((record, index) => {
                                        return (<TableRow key={index} hover>
                                            <TableCell>{record.Title}</TableCell>
                                            <TableCell>{record.Details}</TableCell>
                                            <TableCell>{record.Category}</TableCell>
                                            <TableCell>
                                                <ButtonGroup variant="text">
                                                    <Button><EditIcon color="primary"
                                                        onClick={() => { setCurrentId(record.id) }} /></Button>
                                                    <Button><DeleteIcon color="secondary"
                                                        onClick={() => onDelete(record.id)} /></Button>
                                                </ButtonGroup>
                                            </TableCell>
                                        </TableRow>)
                                    })
                                }
                            </TableBody>
                        </Table> }
                    </TableContainer>

                </Grid>
            </Grid>
        </Paper>
    );
}

const mapStateToProps = state => ({
    courseList: state.course.list
})

const mapActionToProps = {
    fetchAllCourses: actions.fetchAll,
    deleteCourse: actions.Delete
}

export default connect(mapStateToProps, mapActionToProps)(withStyles(styles)(Courses));
Run Code Online (Sandbox Code Playgroud)

动作中的course.js如下:

import api from "./api";

export const ACTION_TYPES = {
    CREATE: 'CREATE',
    UPDATE: 'UPDATE',
    DELETE: 'DELETE',
    FETCH_ALL: 'FETCH_ALL'
}

const formateData = data => ({
    ...data,

})

export const fetchAll = () => dispatch => {
    api.course().fetchAll()
        .then(response => {
            console.log(response)
            dispatch({
                type: ACTION_TYPES.FETCH_ALL,
                payload: response.data
            })
        })
        .catch(err => console.log(err))
}

export const create = (data, onSuccess) => dispatch => {
    data = formateData(data)
    api.course().create(data)
        .then(res => {
            dispatch({
                type: ACTION_TYPES.CREATE,
                payload: res.data
            })
            onSuccess()
        })
        .catch(err => console.log(err))
}

export const update = (id, data, onSuccess) => dispatch => {
    data = formateData(data)
    api.course().update(id, data)
        .then(res => {
            dispatch({
                type: ACTION_TYPES.UPDATE,
                payload: { id, ...data }
            })
            onSuccess()
        })
        .catch(err => console.log(err))
}

export const Delete = (id, onSuccess) => dispatch => {
    api.course().delete(id)
        .then(res => {
            dispatch({
                type: ACTION_TYPES.DELETE,
                payload: id
            })
            onSuccess()
        })
        .catch(err => console.log(err))
}
Run Code Online (Sandbox Code Playgroud)

reducer 中的 course.js 如下:

import { ACTION_TYPES } from "../actions/course";
const initialState = {
    list: []
}


export const course = (state = initialState, action) => {

    switch (action.ACTION_TYPES) {
        case ACTION_TYPES.FETCH_ALL:
            return {
                ...state,
                list: [...action.payload]
            }

        case ACTION_TYPES.CREATE:
            return {
                ...state,
                list: [...state.list, action.payload]
            }

        case ACTION_TYPES.UPDATE:
            return {
                ...state,
                list: state.list.map(x => x.id == action.payload.id ? action.payload : x)
            }

        case ACTION_TYPES.DELETE:
            return {
                ...state,
                list: state.list.filter(x => x.id != action.payload)
            }

        default:
            return state
    }
}
Run Code Online (Sandbox Code Playgroud)

为什么 useEffect 无法访问 props。如何访问 useEffect 中的道具我将非常感谢您的帮助。reducer 中的 index.js 如下:

import { combineReducers } from "redux";
import { course } from "./course";

export const reducers = combineReducers({
    course
})
Run Code Online (Sandbox Code Playgroud)

提前致谢。

Ork*_*zel 12

似乎您需要将所需的依赖项传递给错误消息中提到的 useEffect 。

useEffect(() => {
  props.fetchAllCourses()
}, [props.fetchAllCourses]);
Run Code Online (Sandbox Code Playgroud)

更新:阅读评论中的完整错误消息后,您似乎需要解构道具:

const { fetchAllCourses } = props;

useEffect(() => {
  fetchAllCourses();
}, [fetchAllCourses]);
Run Code Online (Sandbox Code Playgroud)