繁体   English   中英

如何使用axios / AJAX与redux-thunk

[英]How to use axios / AJAX with redux-thunk

我在我的行动中使用axios 我需要知道这是否是正确的做法。

actions/index.js ==>

import axios from 'axios';
import types from './actionTypes'
const APY_KEY = '2925805fa0bcb3f3df21bb0451f0358f';
const API_URL = `http://api.openweathermap.org/data/2.5/forecast?appid=${APY_KEY}`;

export function FetchWeather(city) {
  let url = `${API_URL}&q=${city},in`;
  let promise = axios.get(url);

  return {
    type: types.FETCH_WEATHER,
    payload: promise
  };
}

reducer_weather.js ==>

import actionTypes from '../actions/actionTypes'
export default function ReducerWeather (state = null, action = null) {
  console.log('ReducerWeather ', action, new Date(Date.now()));

  switch (action.type) {
    case actionTypes.FETCH_WEATHER:
          return action.payload;
  }

  return state;
}

然后将它们组合在rootReducer.js ==>中

import { combineReducers } from 'redux';
import reducerWeather from './reducers/reducer_weather';

export default combineReducers({
  reducerWeather
});

最后在我的React容器中调用一些js文件...

import React, {Component} from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {FetchWeather} from '../redux/actions';

class SearchBar extends Component {
  ...
  return (
    <div>
      ...
    </div>
  );
}
function mapDispatchToProps(dispatch) {
  //Whenever FetchWeather is called the result will be passed
  //to all reducers
  return bindActionCreators({fetchWeather: FetchWeather}, dispatch);
}

export default connect(null, mapDispatchToProps)(SearchBar);

我想你不应该(或者至少不应该)将承诺直接放在商店:

export function FetchWeather(city) {
  let url = `${API_URL}&q=${city},in`;
  let promise = axios.get(url);

  return {
    type: types.FETCH_WEATHER,
    payload: promise
  };
}

这样你甚至不使用redux-thunk,因为它返回一个普通的对象。 实际上,redux-thunk使您能够返回稍后将要评估的函数,例如,类似这样的函数:

export function FetchWeather(city) {
  let url = `${API_URL}&q=${city},in`;
  return function (dispatch) { 
    axios.get(url)
      .then((response) => dispatch({
        type: types.FETCH_WEATHER_SUCCESS,
        data: response.data
      })).catch((response) => dispatch({
        type: types.FETCH_WEATHER_FAILURE,
        error: response.error
      }))
  }
}

一定要正确设置redux-thunk中间件。 真的建议阅读redux-thunk文档这篇精彩的文章,以便更深入地了解。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM