2016-04-15 89 views
14

即时通讯使用axios我的行动。我需要知道这是否是正确的做法。如何使用axios/AJAX与还原 - thunk

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); 
+0

如果你使用redux-promise-middleware,这似乎很好。 – Mozak

回答

21

我想你不应该(或至少不应该)直接就把承诺在商店:

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

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

你甚至不使用终极版这样-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 
     }).error((response) => dispatch({ 
     type: types.FETCH_WEATHER_FAILURE, 
     error: response.error 
     }) 
    } 
} 

一定要正确设置了Redux-thunk的中间件。我真的推荐阅读redux-thunk documentationthis amazing article有一个更深入的了解。

+1

我已经想出了答案,一旦到达办公室就会发布代码。它类似 – STEEL

+0

你将需要一个服务器来进行AJAX调用, https://github.com/steelx/ReduxWeatherApp/tree/master/server – STEEL