我如何才能使redux调度操作并返回承诺? [英] How can I make redux dispatch an action as well as return a promise?
问题描述
这是我在songAction.js中的功能
Here is my function in songAction.js
export function createSong(title, url, token) {
axios.defaults.headers.common['Authorization'] = token
return function (dispatch) {
axios.post('http://localhost:8080/api/song/create', {
title,
link: url
})
.then((response) => {
console.log('the response was', response)
if(response.data.success){
dispatch({type: "CREATE_SONG_FULFILLED", payload: response.data.song})
} else {
dispatch({type: "CREATE_SONG_REJECTED", payload: response.data})
}
})
.catch((err) => {
dispatch({type: "CREATE_SONG_REJECTED", payload: err})
})
}
}
我希望能够在分派后返回一个Promise,这样我就可以在组件内部使用这样的功能-
I want to be able to return a promise after dispatching so I can use the function like this inside a component -
createSong(title, url, token)
.then((result) =>{
// do stuff with result
})
我知道我可以传递回调以使此工作异步..但是我想使用promises的ES6功能.我有点困惑我该怎么做.
I know I can pass in a callback to make this work async.. but I want to use ES6 features of promises. And I'm a little confused how I can do this.
推荐答案
我认为使用分派动作的返回值并不是一种非常反应"的方式.
I think that it isn't very 'React' way to use return values of dispatched actions.
有一种更好的方法,可以使用 Redux Saga ,例如此处.
There is a better way how to solve 'complex' situations like this using Redux Saga, example here.
尽管如此,我过去以这种方式使用调度操作返回的值:
Although, I used returned values by dispatched actions in this way in the past:
export const updatePage = (id, batch) => {
return dispatch => {
dispatch({
type: 'UPDATE_PAGE',
payload: {
id
}
})
// Make an API call
return requestUpdatePages(
id, batch
).then(data => {
// When API call is successful
return dispatch({
type: 'UPDATE_PAGE_SUCCESS',
payload: {
id,
data
})
})
.catch(error => {
// When API call fails
return dispatch({
type: 'UPDATE_PAGE_FAIL',
payload: {
error,
id
},
error: true
})
})
}
}
// After dispatch is bound to action creators
// you can use it like this
handleClick(id) {
const { updatePage } = this.props
updatePage(id).then(action => {
if(action.type === 'UPDATE_PAGE_SUCCESS') {
console.log('Whee, page has been updated!', action.payload.data)
} else {
console.error('Something went wrong :-( ', action.payload.error)
}
})
}
这篇关于我如何才能使redux调度操作并返回承诺?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!