下面是我的组件oneroadmap的简要概述:在异步组件didmount中,我首先调用“wait this.props.get roadmaps”,这是我的redux中的一个操作,此操作将向我的API发送一个get请求,该API将从我的数据库中检索项目,然后,从检索到的项目中,我们向reducer发送一个调度,调用get_roadmaps,此做得像
export const getRoadmaps = () => dispatch => {
dispatch(setRoadmapsLoading());
axios
.get("/api/roadmaps")
.then(res => dispatch({ type: GET_ROADMAPS, payload: res.data }));
};
我的组件看起来像:
async componentDidMount() {
await this.props.getRoadmaps();
var location1 = this.props.location.pathname;
var n = location1.slice(9);
var current_roadmaps = this.props.roadmap.roadmaps;
this.displayRoadmap = current_roadmaps.filter(
eachRoadmap => eachRoadmap._id == n
);
// now we have a roadmap
this.setState({
treeData: this.displayRoadmap[0].roadmap[0],
loading: false
});
}
获取路线图将更新我的Redux状态。
问题似乎是:
等待。props.get roadmaps()将只等待get roadmaps()发送调度以获取\u路线图,这意味着它不会等待,直到get roadmaps更新redux状态。
,这意味着几行之后,当我执行这个.props.roadmap.roadmaps时,它将是未定义的,因为这个.props.roadmap.roadmaps可能在get_roadmaps完成更新我的redux状态之前被调用。
如果有什么方法可以解决问题,请指导我:)如果问题不是我想的那样,请纠正我。
参考P.S.I
https://www.robinwieruch.de/react-fetching-data
,上面的信息通常会起作用,但似乎是因为我对Redux商店有额外的调度,调度会在我调用this.props.roadmap.roadmaps后更新商店,这意味着我未定义,无法在渲染中使用该变量。