2017-06-01 79 views
0

我有以下Axios的請求:在何處添加服務器請求功能陣營-Redux的

componentDidMount() { 
    axios.post('http://localhost:3030/api/weather/refresh').then(response => { 
     store.dispatch(refreshWeather(response)) 
    }); 
    } 

此發送派遣終極版,其使用在通用模式喂表象容器。

我的問題是 - 我該如何讓它做到這一點axios.post()請求可重用在應用程序的其他組件或部分?我已經儘可能在導入的外部文件中使用它,但有沒有更好的方法來構建我的項目,以便將所有的axios請求分組在一起?

我有以下mapDispatchToProps:

const mapDispatchToProps = (dispatch, ownProps) => {  
    return { 
    onClickRefresh:() => { 
     dispatch(refreshWeather(arr)) 
    } 
    } 
} 

我想運行的componentDidMount()相同的請求,但不知道的最好的方法,使重複使用如上所述。

感謝

+0

見http://stackoverflow.com/questions/35411423/how-to-dispatch-a-redux -action-with-a-timeout/35415559#35415559,http://stackoverflow.com/questions/34570758/why-do-we-need-middleware-for-async-flow-in-redux/34599594#34599594,以及http://blog.isquaredsoftware.com/2016/10/idiomatic-redux-why-use-action-creators/瞭解如何將異步邏輯移入行動創建者(如thunk)的信息。 – markerikson

回答

2

您可以通過應用redux-thunk中間件並使用中間方法執行請求來完成此操作。

const REFRESH_WEATHER = 'REFRESH_WEATHER'; 

export const requestWeather =() => dispatch => { 
    axios.post('http://localhost:3030/api/weather/refresh').then(response => { 
     dispatch(refreshWeather(response)); 
    }); 
}; 

const refreshWeather = (response) => { 
    return { 
     type: REFRESH_WEATHER, 
     response, 
    }; 
} 

如果你發現自己賺了很多,你可以打造出自己的API中間件來處理所有請求重複類似的請求。

1

在終極版的模式是使用異步操作的創造者,這樣它可以被重新使用,就像任何其他行動的創造者,並映射到你的道具。

official docs中有一個很好的例子來說明如何做到這一點。

1

config.js

module.exports = { 
    API_URL: 'http://localhost:3030/api', 
}; 

makeRequest.js

import axios from 'axios'; 
import { API_URL } from './config'; 

module.exports = (path, method, ...args) => axios[method](API_URL + path, ...args); 

actions.js

module.exports.refreshWeather = (newWeather) => ({ 
    type: 'REFRESH_WEATHER', 
    payload: newWeather, 
}); 

stories.js

import makeRequest from './makeRequest'; 
import { refreshWeather as refreshWeatherAction } from './actions'; 

module.exports.resfreshWeatherStory = (dispatch) => (
    makeRequest('/weather/refresh', 'post') 
     .then(response => dispatch(refreshWeatherAction(response))); 
); 

YourComponent.js

... 
import { refreshWeatherStory } from './stories'; 
... 
componentDidMount() { 
    refreshWeatherStory(store.dispatch); 
} 
... 

OtherPlace.js

... 
import { refreshWeatherStory } from './stories'; 

const mapDispatchToProps = dispatch => ({ 
    onClickRefesh:() => refreshWeatherStory(dispatch), 
}); 
... 

你的想法