内部使用效应永远不会在React-Redux应用程序中运行



i具有以下组件。我确实调试了。useEffect中的功能永远不会被调用。代码到达useEffect,但不输入内部,因此不会从数据库中获取记录。有什么想法为什么会发生这种情况?

import * as React from 'react';
import { useEffect } from 'react';
import { connect } from 'react-redux';
import { FetchAssignmentData } from './AssignmentDataOperations'
const AssignmentComprehensive = (props) => {
    useEffect(() => {
        if (props.loading != true)
            props.fetchAssignment(props.match.params.id);
    }, []);
    if (props.loading) {
        return <div>Loading...</div>;
    }
    if (props.error) {
        return (<div>{props.error}...</div>)
    }
    //these are always null
    const assignmentId = props.assignmentIds[0];
    const assignment = props.assignments[assignmentId];
    return (
        //this throws error since the values are never fetched from db
        <div>{props.assignments[props.assignmentIds[0]].title}</div>
    );
}
const mapStateToProps = state => ({
    assignmentIds: state.assignmentReducer.assignmentIds,
    assignments: state.assignmentReducer.assignments,
    submissions: state.assignmentReducer.submissions,
    rubric: state.assignmentReducer.rubric,
    loading: state.assignmentReducer.loading,
    error: state.assignmentReducer.error
})
const mapDispatchToProps = dispatch => {
    return { fetchAssignment: (id) => dispatch(FetchAssignmentData(id)) };
}
export default connect(
    mapStateToProps,
    mapDispatchToProps
)(AssignmentComprehensive);

因为useEffect第二参数:

https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-byskipping-effects

如果您想运行效果并仅清理一次(在安装和卸载上(,则可以将空数组([](作为第二个参数传递。这告诉React,您的效果不取决于道具或状态的任何值,因此它不需要重新运行。

因此,它仅运行一次(当props.loadingtrue时(而再也不会运行。

您似乎有3个依赖性:

useEffect(() => {
  ...
}, [props.loading, props.fetchAssignment, props.match.params.id])

另请参见:react-hooks/exhaustive-deps ESLINT规则。

相关内容

  • 没有找到相关文章

最新更新