【发布时间】:2020-09-24 05:09:22
【问题描述】:
我有一个 util/usedecoder.ts 文件,如下所示:
import axios from 'axios';
export const decoder = ({latitude, longitude}: any) => {
const url =
'https://api.opencagedata.com/geocode/v1/json?q=' +
latitude +
'+' +
longitude +
'&key=########';
axios
.get(url)
.then(function (response: any) {
const timestamp = response.data.timestamp.created_http;
const address = response.data.results.filter((data: any) => data.confidence > 8)[0].formatted;
return {timestamp, address};
})
.then((data) => {
console.log(data);
dispatch(addLocation(data)); <-------- Not working
})
.catch(function (error: string) {
console.log(error);
});
};
export function addLocation(data: any) {
return {
type: 'ADD_LOCATION',
data: data,
};
}
我的文件对调度方法一无所知。为什么这样?我是不是在 App 级别配置了错误?
我的 index.tsx:
import React from 'react';
import App from './App';
import {Provider} from 'react-redux';
import {createStore, applyMiddleware, compose} from 'redux';
import {rootReducer} from './redux';
import thunk from 'redux-thunk';
export default class Root extends React.Component {
public render() {
const store = createStore(rootReducer, applyMiddleware(thunk));
return (
<Provider store={store}>
<App />
</Provider>
);
}
我的 App.tsx 看起来像:
import {useGeolocation} from './utils/useGeolocation';
import {decoder} from './utils/useDecoder';
import Home from './screens/Home';
import * as React from 'react';
const App = () => {
const geoLocation = useGeolocation();
decoder(geoLocation[1]);
return <Home />;
};
export default App;
如何使用 useDecoder 中的调度功能?
【问题讨论】:
-
dispatch不是全局函数。您必须将其提供给decoder。使用异步 redux 操作。
标签: reactjs react-native redux react-redux redux-thunk