我有三个独立的useEffect
函数。一种是获取提交记录:
useEffect(() => {
if (props.loading_submissions != true) {
props.fetchSubmissionsByReviewRound(reviewRoundId);
}
}, [reviewRoundId])
另一个是用来吸引学生的。
useEffect(() => {
if (props.loading_students != true) {
props.fetchStudentsByCourse(courseId, reviewRoundId);
}
}, [reviewRoundId])
我更喜欢首先获取Students
,并且一旦加载并保存它们为redux状态,就应该获取提交内容。我不知道如何实现这一目标。任何帮助表示赞赏。
下面是mapStateToProps
和mapDispatchToProps
方法:
const mapStateToProps = (state) => ({
submissions: state.submissionReducer.submissions,
students: state.studentReducer.students,
loading_students: state.studentReducer.loading,
loading_submissions: state.submissionReducer.loading,
error: state.studentReducer.error,
})
const mapDispatchToProps = (dispatch) => {
return {
fetchSubmissionsByReviewRound: (reviewRoundId) => dispatch(FetchSubmissionsByReviewRound(reviewRoundId)),
fetchStudentsByCourse: (courseId, reviewRoundId) => dispatch(FetchStudentsByCourse(courseId, reviewRoundId)),
}
}
我正在使用axios
来获取数据:
export function FetchStudentsByCourse(courseId, reviewRoundId) {
return dispatch => {
dispatch(studentsDataOperationBegin());
axios.get("api/Student/FetchStudentsByCourse", { params: { courseId, reviewRoundId } })
.then(response => {
console.log('Students in the course are fetched by course id.');
const students = new schema.Entity('students');
const normalizedData = normalize(response.data, [students]);
dispatch(fetchStudentsSuccess(normalizedData.entities.students))
})
.catch(error => { studentsDataOperationFailure(error) });
}
}
export function FetchSubmissionsByReviewRound(reviewRoundId) {
return dispatch => {
dispatch(submissionDataOperationBegin());
axios.get('api/Submission/FetchSubmissionsByReviewRound', { params: { reviewRoundId } })
.then(response => {
console.log('Submissions are fetched.');
const submissions = new schema.Entity('submissions');
const normalizedData = normalize(response.data, [submissions]);
dispatch(fetchSubmissionsByReviewRoundSuccess(normalizedData.entities.submissions))
})
.catch(error => { submissionDataOperationFailure(error) });
}
}
答案 0 :(得分:2)
如果您希望它们中的一个依赖于另一个,那么我将在一个useEffect()方法下将它们加入,并从它们中做出promise函数。完成后,async / await将成为您的朋友。
但是,如果您希望将Student调用中的数据加载到用户,然后浏览器获取另一个数据,那么我将使用第2个setState来监视由修改的第2个调用第一。像这样:
const [studentDataReceived, setStudentDataReceived] = useState(false);
useEffect(() => {
if (props.loading_students != true) {
props.fetchStudentsByCourse(courseId, reviewRoundId);
}
setStudentDataReceived(true)
}, [reviewRoundId])
useEffect(() => {
if(studentDataReceived){
if (props.loading_submissions != true) {
props.fetchSubmissionsByReviewRound(reviewRoundId);
}
}
}, [studentDataReceived])