Javascript 如何在 redux-thunk 中使用 axios/AJAX

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36640527/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:21:04  来源:igfitidea点击:

How to use axios / AJAX with redux-thunk

javascriptreactjsreduxredux-thunkaxios

提问by STEEL

Im using axiosinside my action. I need to know if this is the right way to do it or not.

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

actions/index.js==>

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==>

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

and then come combining them inside rootReducer.js==>

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

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

export default combineReducers({
  reducerWeather
});

And finally calling it inside my React container some js file...

最后在我的 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);

回答by falsarella

I guess you shouldn't (or at least not supposed to) put the promise directly at the store:

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

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

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

This way you are not even using redux-thunk, because it's returning a plain object. Actually, redux-thunk, enables you to return a function that will be evaluated later, for example, something like this:

这样你甚至不用 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
      }))
  }
}

Be sure to properly setup the redux-thunk middleware. I really recommendreading redux-thunk documentationand this amazing articleto have a deeper understanding.

确保正确设置 redux-thunk 中间件。我真的建议您阅读redux-thunk 文档这篇精彩的文章,以有更深入的了解。