在何处添加服务器请求功能阵营-Redux的
问题描述:
我有以下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()相同的请求,但不知道的最好的方法,使重复使用如上所述。
感谢
答
您可以通过应用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中间件来处理所有请求重复类似的请求。
答
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),
});
...
你的想法
见http://*.com/questions/35411423/how-to-dispatch-a-redux -action-with-a-timeout/35415559#35415559,http://*.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