从后端获取课程后,我试图找到一门课程,但是在获取内容后进入状态时,该状态为初始课程。 在安装组件时调用此功能
findCourse = async () => {
const { props, state } = this;
const { idCourse } = state;
const { loadCourseInfoProps, findCourse } = props;
await loadCourseInfoProps(idCourse);// goes to the back end and fetches the course and its updated the state
const course1 = findCourse(idCourse); // this functions should go to the updated state in the store and find the course with the id
console.log(course1);
};
映射器
const mapStateToProps = (state:any) => ({
findCourse: (id:any) => getCourseSelector(state, id),
});
const mapDispatchToProps = (dispatch:Dispatch) => ({
loadCourseInfoProps: (id:any) => dispatch(loadCourseInfo(id)),
});
export default connect(mapStateToProps, mapDispatchToProps)(withRouter(CourseInfoN));
我创建的吸气剂
export const getCourseSelector = (state:any, id:number) =>{
console.log(state)
return(
state.courses.courses.find((course:any) => course.course_data.idCourse === id)
)};
还有异常行为
export const loadCourseInfo = (id:any) => async (dispatch:Dispatch, getState:any) => {
dispatch(loadCourseInfoRequest());
const state = getState();
if (state.courses.courses.length !== 0) {
const courseWithId = state.courses.courses.find((course:any) => course.course_data.idCourse === id);
if (courseWithId.meta.contains_all || !courseWithId) {
return;
}
}
try {
const course = await ApiService.courses.getCourse(id);
console.log(course)
const formattedCourse = courseFormatter(course);
formattedCourse.meta.contains_all = true;
dispatch(loadCourseInfoSuccess(formattedCourse));
console.log("finished")
} catch (error) {
console.log("[error][1]", error);
dispatch(loadCourseInfoFail(error));
}
};
在图像中,您可以看到已完成的日志已打印,并且此时已完成了变异,但是getter中的下一个console.log状态仍然为空 图片链接:https://i.stack.imgur.com/Yuglp.png
答案 0 :(得分:1)
您不应期望在同一函数调用中出现更新状态。如果您希望拥有新的状态,则可能应该在收到状态的同一操作中对其进行处理:
export const loadCourseInfo = (id:any) => async (dispatch:Dispatch, getState:any) => {
...
const course = await ApiService.courses.getCourse(id);
// use it right here
};
或者您可以在下一个渲染器上使用更新的状态。