我试图从后端获取课程后找到课程,但是当我在获取后进入状态时,状态是初始状态。 安装组件时调用此函数
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)
)};
和 aync 动作
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