簡體   English   中英

forEach - 將鍵/值添加到 Redux 中的 action.data - console.log 有效,但 Redux state 未更新

[英]forEach - adding key/value to action.data in Redux - console.log works but Redux state not updated

在異步 Redux 操作中,我使用 graphQL 收集一些數據,然后調用另一個異步操作,該操作在 object 中循環(使用 forEach)並添加一些鍵。

UserTopicActions.js


export const sendGetUserTopicSuccess = data => ({
    type: action_types.SEND_GET_USER_TOPIC_SUCCESS,
    data
});
 ...

export function sendGetUserTopic(user_id, nextToken = null) {
    return async (dispatch) => {
        dispatch(sendGetUserTopicBegin());
        ...
        try {
            const data = await API.graphql(graphqlOperation(gqlUserTopic.getUserTopic, variables))
            data_uri = await getCarouselImgUri(data.data.getUserTopic)
            dispatch(sendGetUserTopicSuccess(data_uri));

        } catch (err) {
            dispatch(sendGetUserTopicFailure(err));
        }
    };
}

amplifyAsync.js

import { Storage } from 'aws-amplify';

export default async function getCarouselImgUri(raw_data) {
    data = JSON.parse(raw_data.data)
    topics = data.topics
    // Fetching thumbnails for cards
    let card_img_uri
    topics.forEach((topic) => {
        topic['subtopics'].forEach(async (subtopic) => {
            card_img_uri = 'topic/' + topic.id + '/' + subtopic.id + '/' + 'thumbnail.jpg'
            subtopic['uri'] = await Storage.get(card_img_uri)      <------------ New Key!
        })
    })
    console.log(topics)
    return topics

}

UserTopicReducer.js

export default (state = initialState, action) => {
    switch (action.type) {
        case SEND_GET_USER_TOPIC_BEGIN:
            return {
                ...state,
                isGettingUserTopic: true,
            };
        case SEND_GET_USER_TOPIC_SUCCESS:
            console.log(action.data)
            return {
                ...state,
                isGettingUserTopic: false,
                topics: action.data
            };
    ...

如果我在 reducer 中控制台記錄 action.data,我會看到新鍵。 另一方面,在state 和調度的SEND_GET_USER_TOPIC_SUCCESS操作中,新密鑰不存在。

為什么? 如何在 Redux 異步操作的數據中添加新鍵?

經過幾個痛苦的小時后,我發現了錯誤:

amplifyAsync.jsAsync... wait並不能確保forEach()中的所有承諾都已解決。

我認為最好的解決方案是將所有承諾放在一個數組中,然后使用 promise.all,但是因為我想保持相同的字典結構(並且 promise.all 不適用於字典),所以我暫時使用了普通的外觀和異步等待。 這樣,所有請求都按順序完成。 這是一個非優化的解決方案,但現在它可以工作。

在調試承諾時,請確保您執行console.log(JSON.stringify(data))否則標准的console.log(data)可能會打印解析的 promise 的值,該值在執行時可能不可用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM