【发布时间】: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