我需要借助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;
不幸的是,我不知道该怎么做。在组件中以这种方式获取数据之前:
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来获取数据,所以,请您能解释一下如何完成此获取部分,我应该在这里添加什么?
在佐贺中,请导入这些东西
import { put } from 'redux-saga/effects'; 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 { yield put({ type: LIST_RESPONSE, payload: data }); } };
在减速器中
switch (action.type) { case Actions.LIST_RESPONSE: return { ...state, list: action.payload, };