2016-04-15 13 views
14

Im使用するaxios私の行動の中に。私はこれが正しいかどうかを知る必要があります。axios/AJAX with redux-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 
}); 

そして最後に呼び出し内でそれらを組み合わせて来ますそれは私のリアクションコンテナsomの中に

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

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

あなたもReduxのを使用していないこの方法:電子の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

私はあなたが(または少なくともになっていない)べきではないと思いますが店頭で直接約束を置きますそれは普通のオブジェクトを返すからです。実際には、Reduxの-サンク、後で評価される関数を返すことができ、例えば、このような何か:

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の-サンクミドルウェアにしてください。私は本当にお勧めredux-thunk documentationthis amazing articleを読んでより深い理解を持ってお勧めします。

+1

答えがわかりました。私がオフィスに着くとコードを投稿します。それは似ている – STEEL

+0

あなたは、AJAXの呼び出しを行うためにサーバーが必要です https://github.com/steelx/ReduxWeatherApp/tree/master/server – STEEL

関連する問題