我使用 ng-redux angular 2 中的模块,我不知道执行异步操作的更好方法是什么。例如我需要从服务器获取一些数据。我可以使用异步操作创建器来做到这一点 redux-thunk中间件: 我将创建一个返回函数的操作:
export function fetchData() {
return function (dispatch) {
dispatch({
type: 'FETCH_DATA_REQUEST'
});
return fetch(url)
.then(response => response.json())
.then(json => dispatch({type: 'FETCH_DATA_SUCCESS', data: json}))
.catch(error => dispatch({type: 'FETCH_DATA_ERROR', error: error
}
}
}
dispatch(fetchData());
或者我可以在 Controller 中做 HTTP 请求,我将手动执行调度方法:
dispatch({
type: 'FETCH_DATA_REQUEST'
});
http(url).then(data => {
dispatch({
type: 'FETCH_DATA_SUCCESS',
data: json
});
}).catch(error => {
dispatch({
type: 'FETCH_DATA_ERROR',
error: error
});
});
推荐哪种方法?我认为第二种方法更简单,但为什么会有 redux-thunk 中间件。
最佳答案
绝对推荐第一种方法,尤其是在您使用中间件库的情况下。
唯一要记住的是在 ComponentDidMount
React 生命周期方法中分派(dispatch)您的操作。
关于angular - 在 angular 2 中的 redux 中执行异步操作的推荐方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38252985/