我有一个类似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,
};
}
我的文件对分派方法一无所知。为什么这样?我在应用程序级别上配置了错误吗?
我的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中使用调度功能?
答案 0 :(得分:1)
假设您已经使用redux-thunk中间件设置/配置了商店,并将应用程序/组件正确连接到商店,那么您的操作创建者只需要返回一个接收{{1} }。
dispatch
答案 1 :(得分:0)
I solved it by using a hook:
import axios from 'axios';
import {useDispatch} from 'react-redux'; ---->
export const decoder = ({latitude, longitude}: any) => {
const dispatch = useDispatch();
const url =
'https://api.opencagedata.com/geocode/v1/json?q=' +
latitude +
'+' +
longitude +
'&key=30eb4ee11aeb43848e1db3a7056ad91f';
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) => {
dispatch(addLocation(data));
})
.catch(function (error: string) {
console.log(error);
});
};
export function addLocation(data: any) {
return {
type: 'ADD_LOCATION',
data: data,
};
}