【发布时间】:2019-12-12 18:20:47
【问题描述】:
我需要借助 Redux 等工具从服务器获取数据。我看了一些关于它的教程并为它写了一些代码。这里是:
actions/fetching_actions.js
import * as Actions from '../constants/action_types';
function fetchListOfCities() {
return fetch(`${Actions.BASE_URL}/data/2.5/find?lat=55.5&lon=37.5&cnt=10&appid=8df903ce56f6d18245e72f380beb297d`);
}
export const listOfCitiesRequest = () => function (dispatch) {
return fetchListOfCities()
.then(list => list.json())
.then((list) => {
dispatch(getListOfCities(list));
}).catch((error) => {
console.log(error);
});
};
export const getListOfCities = result => ({
type: Actions.LIST_RESPONSE,
result,
});
常量/action_types.js
export const BASE_URL = 'http://api.openweathermap.org';
export const LIST_RESPONSE = 'LIST_RESPONSE';
export const CITY_RESPONSE = 'CITY_RESPONSE';
reducers/fetching_reducer.js
import * as Actions from '../constants/action_types';
const initialState = {
list: [],
city: {},
};
const FETCHING_REDUCER = (state = initialState, action) => {
switch (action.type) {
case Actions.LIST_RESPONSE:
return {
...state,
list: action.result,
};
case Actions.CITY_RESPONSE:
return {
...state,
city: action.result,
};
default:
return state;
}
};
export default FETCHING_REDUCER;
reducers/index.js
import * as Actions from '../constants/action_types';
const initialState = {
list: [],
city: {},
};
const FETCHING_REDUCER = (state = initialState, action) => {
switch (action.type) {
case Actions.LIST_RESPONSE:
return {
...state,
list: action.result,
};
case Actions.CITY_RESPONSE:
return {
...state,
city: action.result,
};
default:
return state;
}
};
export default FETCHING_REDUCER;
不幸的是,我不知道我应该进一步做什么。在我以这种方式在 Component 中获取数据之前:
getCitiesListFromApiAsync = async () => {
const fetchData = await fetch('http://api.openweathermap.org/data/2.5/find?lat=55.5&lon=37.5&cnt=10&appid=8df903ce56f6d18245e72f380beb297d').then();
const data = await fetchData.json();
if (data.cod !== '200') {
Alert.alert('Loading failed');
} else {
this.setState({ data });
}
};
但是我听说用redux取数据比较好,所以,请你解释一下如何完成这个取数据,我应该在这里添加什么?
【问题讨论】:
-
你需要
connect你的组件到数据存储区。 -
请点击此链接。我希望它有所帮助:) https://stackoverflow.com/a/38729447/3840665
-
对于异步操作,您需要使用一些中间件,如 redux-thunk 来执行此操作。 github.com/reduxjs/redux-thunk/blob/master/src/index.js