【问题标题】:React await for data fetch with axios to happen before triggering next line is not working在触发下一行之前反应等待使用 axios 获取数据不起作用
【发布时间】:2019-01-28 21:26:42
【问题描述】:

这里是我的组件 OneRoadmap 的简要概述:在异步 componentDidMount 中,我首先调用“await this.props.getRoadmaps”,这是我的 Redux 中的一个动作,这个动作将向我的 api 发送一个 get 请求,它将检索我的数据库中的项目,然后,从检索到的那些项目中,我们向 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
});
}

GET_ROADMAPS 将更新我的 Redux 状态。

问题似乎是:await this.props.getRoadmaps() 只会等到 getRoadmaps() 将调度发送到 GET_ROADMAPS,这意味着它不会等到 GET_ROADMAPS 更新 redux 状态 ,这意味着几行之后,当我执行 this.props.roadmap.roadmaps 时,它将是未定义的,因为 this.props.roadmap.roadmaps 可能在 GET_ROADMAPS 完成更新我的 redux 状态之前被调用。

如果有任何方法可以解决问题,请指导我:) 如果问题不是我认为的问题,请纠正我。

附:我引用了https://www.robinwieruch.de/react-fetching-data,那里的这个信息通常会起作用,但似乎因为我有一个额外的调度到我的 redux 存储,所以调度会在我调用 this.props.roadmap.roadmaps 后更新存储,这意味着我得到了未定义且无法在我的渲染中使用该变量

【问题讨论】:

  • 能否请您发布完整的getRoadmaps 功能。它也应该是异步的,或者你需要做return axios.get(...).then(...)
  • 抱歉,我更新了我的问题,我会按照您的建议更改我的代码
  • 我认为是用箭头函数返回的
  • 不,因为你把它放在一个块中,你必须明确地返回。

标签: javascript reactjs redux react-redux axios


【解决方案1】:

看来你没有返回你的动作创建器。创建块时必须显式返回(使用花括号)。

返回您的 axios 调用,它应该可以正常工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-25
    • 1970-01-01
    • 2020-08-06
    • 2020-08-19
    • 1970-01-01
    • 2020-10-01
    • 2019-08-09
    • 2013-02-12
    相关资源
    最近更新 更多