【问题标题】:How to return a promise in redux actions - react native如何在 redux 操作中返回承诺 - 反应原生
【发布时间】:2020-04-06 21:34:32
【问题描述】:

我正在尝试在需要时从 redux 获取位置。在 redux 将位置保存到状态后,我需要返回一个承诺,因为我需要在我的屏幕上显示该数据。

这是我的操作、reducers、store 以及我如何使用它们。

LocationRedux.tsx

import * as Type from './LocationReduxTypes';
const initialState: Type.LocationState = {
    location: undefined,
};
const LocationRedux = (
    state = initialState,
    action: Type.LocationActionTypes,
): Type.LocationState => {
    switch (action.type) {
        case Type.SET_LOCATION:
            return { ...state, location: action.location };
        default:
            return state;
    }
};

export { LocationRedux as default };

LocationReduxActions.tsx - 在这里我需要返回一个承诺,当我使用此方法时,我需要知道位置已解决。

import * as Type from './LocationReduxTypes';
import Store from '~/Redux/Store';

import { GeolocationResponse } from '@react-native-community/geolocation';

class LocationReduxActions {
    public static SetLocation(location: GeolocationResponse) {
        return new Promise((resolve, reject) => {
            resolve(
                Store.instance.dispatch({
                    type: Type.SET_LOCATION,
                    location,
                }),
            );
            reject(
                console.log('rejected'),
            );
        });

    }
}

export { LocationReduxActions as default };

LocationReduxType.tsx

import { MenuItemType } from '~/Helpers/Menu';
import { GeolocationResponse } from '@react-native-community/geolocation';

export const SET_LOCATION = 'SET_LOCATION';

interface SetLocationAction {
    type: typeof SET_LOCATION;
    location?: GeolocationResponse;
}

export interface LocationState {
    location?: GeolocationResponse;
}
export type LocationActionTypes = SetLocationAction;

这就是我尝试使用此操作的方式。

    componentDidMount() {
        if (!this.props.location) {
            Geolocation.getCurrentPosition(location => {
                LocationReduxActions.SetLocation(location)
                .then(() => { // debugger never hit this then method.
                    this._load();
                });
            }, () => { // error handling.
                this._load();
            });
        } else { 
            this._load(); 
        }
    }

任何帮助将不胜感激,谢谢。

【问题讨论】:

    标签: javascript reactjs typescript react-native promise


    【解决方案1】:

    我认为 then 被调用了,你确实从 SetLocation 返回了一个 Promise,并解决了它。

    另外,请注意 dispatch 是同步的,因此您不需要承诺:商店一旦被调用就会更新。

    顺便说一句,如果您想根据商店中的内容更新您的 UI,更简单且常用的方法是react-redux

    【讨论】:

      猜你喜欢
      • 2020-05-11
      • 2018-04-26
      • 2021-06-20
      • 2018-01-08
      • 2019-11-03
      • 1970-01-01
      • 2020-04-13
      • 2020-08-05
      • 2017-07-16
      相关资源
      最近更新 更多