gpt4 book ai didi

javascript - 如何在 redux 操作中返回 promise - React Native

转载 作者:行者123 更新时间:2023-11-28 03:19:17 27 4
gpt4 key购买 nike

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

这是我的操作、 reducer 、存储以及我如何使用它们。

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 - 这里我需要返回一个 promise ,当我使用此方法时,我需要知道位置已解析。

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();
}
}

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

最佳答案

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

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

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

关于javascript - 如何在 redux 操作中返回 promise - React Native,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59322444/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com