【问题标题】:How to map and object based on another object如何基于另一个对象映射和对象
【发布时间】:2021-11-23 12:16:25
【问题描述】:

所以我调用了一个 api 并将结果存储在一个名为 shift 的状态中并得到以下结果:

[
    {
        "id": 123,
        "status": "created",
        "expected": {
            "end_time": "2021-10-01",
            "start_time": "2021-10-01"
        },
    },
    {
        "id": 567,
        "status": "created",
        "expected": {
            "end_time": "2021-09-30",
            "start_time": "2021-09-30"
        },
    }
]

现在正在通过以下方式映射此转变状态:

{shift.map((item: any, key: any) => (
    <>
        <ShiftComponent
            Name={'name'}
            StartTime={item.expected.start_time}
            EndTime={item.expected.end_time}
            Address={'address'}
        />
    </>
))}

要获得这个nameaddress,我必须使用第一个api 中的id 调用另一个api,所以我从数组中的第一个api 中提取了id:

id = ["123", "567"]

然后调用第二个api并将结果存储在value状态:

for (let i = 0; i < id.length; i++) {
    ApiCall.get(Url + 'value/' + id[i])
        .then(async (resp) => {
            if (resp) {
                setValue(resp.data);
            } else {
                Alert.alert('Error', resp);
            }
        })
        .catch((err: any) => {
            console.log(err);
        });
}

第二个api的结果:

{  
    "address": {
        "state": "anice state",
        "city": "nice city",
    },
    "name": "Nice name",
    "id": "123"
}
{  
    "address": {
        "state": "anice state 2",
        "city": "nice city 2",
    },
    "name": "Nice name 2",
    "id": "567"
}

根据第二个 api 的结果,我如何在ShiftComponent 中提供姓名和地址。我尝试在已映射的shift 上进行映射,但这会产生重复和错误的输出。

P.S.:我在我的 api 调用中只显示了 2 个示例输出,实际上还有更多

请帮忙,我找不到解决办法。!!

【问题讨论】:

    标签: javascript reactjs typescript react-native mapping


    【解决方案1】:

    如果您确实需要为每个 id 单独调用 API,您可能希望将此调用移至 ShiftComponent 或将其包装在另一个负责该调用的组件中。你现在的做法有一个缺陷:

    for (let i = 0; i < id.length; i++) { // <-- this is a loop
        ApiCall.get(Url + 'value/' + id[i])
            .then(async (resp) => {
                if (resp) {
                    setValue(resp.data); // <-- this will overwrite state with every API response
                } else {
                    Alert.alert('Error', resp);
                }
            })
            .catch((err: any) => {
                console.log(err);
            });
    }
    

    在这样的循环中调用 setValue 意味着您只保留来自 API 的最新响应。同样,最简单的解决方案是在每个子组件中进行一次 API 调用。它可能看起来像这样:

    {shift.map((item: any, key: any) => (
        <ShiftComponent // make the API call inside this component
            id={item.id}
            StartTime={item.expected.start_time}
            EndTime={item.expected.end_time}
        />
    ))}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-27
      • 1970-01-01
      • 2018-02-10
      相关资源
      最近更新 更多