【问题标题】:How to fetch data from server with redux?如何使用 redux 从服务器获取数据?
【发布时间】: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取数据比较好,所以,请你解释一下如何完成这个取数据,我应该在这里添加什么?

【问题讨论】:

标签: reactjs redux


【解决方案1】:

在 saga 中请导入这些东西

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,
      };

【讨论】:

    【解决方案2】:

    要通过 redux 向服务器发送一些请求,您应该使用 middlewares 之一:

    1. redux-thunk
    2. redux-promise
    3. redux-saga
    4. redux-observable

    我认为最简单的是 redux-thunk。

    1.安装包:

    $ npm install redux-thunk
    

    2。将其连接到您的商店:

    import { createStore, applyMiddleware } from 'redux';
    import thunk from 'redux-thunk';
    import rootReducer from './reducers/index';
    
    // Note: this API requires redux@>=3.1.0
    const store = createStore(
      rootReducer,
      applyMiddleware(thunk)
    );
    

    之后,您将被允许向 redux 分发一个普通的 javascript 对象和函数。

    3.所以你可以这样调度:

    store.dispatch(listOfCitiesRequest());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-26
      • 1970-01-01
      • 2014-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多