我有以下内容。我做了调试。 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);
答案 0 :(得分:1)
由于第二个参数useEffect
:
https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects
如果要运行效果并仅将其清理一次(在挂载和卸载时),则可以将空数组([])作为第二个参数传递。这告诉React,您的效果不依赖于道具或状态的任何值,因此它不需要重新运行。
因此它仅运行一次(props.loading
为true
时),并且再也不会运行。
您似乎有3个依赖项:
useEffect(() => {
...
}, [props.loading, props.fetchAssignment, props.match.params.id])
另请参阅:react-hooks/exhaustive-deps
eslint rule。