You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中Array Map内设置值无效问题求助

问题分析与修复方案

Hey, I see exactly what's tripping you up here — it's all about the timing of your async operations. Let's break this down:

Why this is happening

When you loop through your members with map, you're firing off an async request with EscortService.getLastEscorts, but you immediately return the original member right away. The then callback where you call member.setEscortHistory doesn't run until later, after the API call finishes.

By the time you call this.setState({ members: membersWithEscorts }), none of those setEscortHistory calls have actually executed yet. So your child component gets the raw members with no escort history attached. Even if the setEscortHistory runs later, you never tell React to re-render with the updated data, so the child component never sees the changes.

How to fix it

We need to wait for all those escort history API calls to finish before updating our component state. Here's how to adjust your code:

componentDidMount() {
  const { storeId, store } = Auth.user();
  MemberService.getByStore(storeId).then((members) => {
    const options = {
      fromDate: this.state.period.from,
      toDate: this.state.period.to,
    };

    // First, create an array of promises that resolve to members WITH their escort history
    const memberPromises = members.map((member) => {
      return EscortService.getLastEscorts(member.id, options)
        .then((escorts) => {
          member.setEscortHistory(new EscortHistory(escorts));
          return member; // Return the updated member once the async call finishes
        });
    });

    // Wait for ALL promises to resolve, then update state
    Promise.all(memberPromises).then((membersWithEscorts) => {
      this.setState({ members: membersWithEscorts, store });
    });
  });
}

Extra notes

  • If your member objects are immutable (like if you're using Immutable.js), calling setEscortHistory directly might not work — you'll need to return a new instance of the member with the updated escort history instead. For example:
    return EscortService.getLastEscorts(member.id, options)
      .then((escorts) => {
        return member.set('escortHistory', new EscortHistory(escorts));
      });
    
  • You might want to add a loading state (like a spinner) while these API calls are in flight — it'll make the UX smoother instead of showing an empty list briefly.

内容的提问来源于stack exchange,提问作者sseggio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:16:32