Redux async actioncreator 无法识别
Redux async actioncreator not recognizing then
我需要在 redux 操作上使用 .then()
,下面的操作有什么问题?
export const userLogin = (username, password) => {
return dispatch => {
axios.post(`${TT_API_BASE}/Access/Login`, { username: username, password: password, applicationId: 2 }, {
headers: {
'Content-Type': 'application/json;charset=utf-8',
'Authorization': 'Basic ' + auth,
}
})
.then(response => {
dispatch({
type: LOGIN,
payload: response.data
})
})
.catch(err => {
console.log(err)
dispatch({
type: LOGIN_FAILED
})
})
}
}
然后在这样的组件中调用它
handlePress() {
this.props.userLogin(this.state.username, this.state.password)
.then(() => {
this.props.navigation.navigate('SelectInstance')
})
}
显示未定义的错误消息。我做错了什么?
当您执行 dispatch(someThunkActionCreator())
时,dispatch
的 return 值就是您的 thunk 函数 returns。因此,如果 thunk 函数 return 是一个承诺,您只能执行 dispatch().then()
。
你的 thunk 正在进行 AJAX 调用,但实际上并没有 return 承诺,所以它实际上 returns undefined
。在 axios.post()
前面放置一个 return
语句将 return 承诺并解决问题。
这样做解决了:
export const userLogin = (username, password) => {
return async dispatch => {
const onSuccess = data => {
dispatch({
type: LOGIN,
payload: data
})
}
const onError = err => {
dispatch({
type: LOGIN_FAILED
})
}
try {
const req = await axios.post(`${TT_API_BASE}/Access/Login`, { username: username, password: password, applicationId: 2 }, {
headers: {
'Content-Type': 'application/json;charset=utf-8',
'Authorization': 'Basic ' + auth,
}
})
return onSuccess(req.data)
}
catch (err) {
return onError(err)
}
}
}
我需要在 redux 操作上使用 .then()
,下面的操作有什么问题?
export const userLogin = (username, password) => {
return dispatch => {
axios.post(`${TT_API_BASE}/Access/Login`, { username: username, password: password, applicationId: 2 }, {
headers: {
'Content-Type': 'application/json;charset=utf-8',
'Authorization': 'Basic ' + auth,
}
})
.then(response => {
dispatch({
type: LOGIN,
payload: response.data
})
})
.catch(err => {
console.log(err)
dispatch({
type: LOGIN_FAILED
})
})
}
}
然后在这样的组件中调用它
handlePress() {
this.props.userLogin(this.state.username, this.state.password)
.then(() => {
this.props.navigation.navigate('SelectInstance')
})
}
显示未定义的错误消息。我做错了什么?
当您执行 dispatch(someThunkActionCreator())
时,dispatch
的 return 值就是您的 thunk 函数 returns。因此,如果 thunk 函数 return 是一个承诺,您只能执行 dispatch().then()
。
你的 thunk 正在进行 AJAX 调用,但实际上并没有 return 承诺,所以它实际上 returns undefined
。在 axios.post()
前面放置一个 return
语句将 return 承诺并解决问题。
这样做解决了:
export const userLogin = (username, password) => {
return async dispatch => {
const onSuccess = data => {
dispatch({
type: LOGIN,
payload: data
})
}
const onError = err => {
dispatch({
type: LOGIN_FAILED
})
}
try {
const req = await axios.post(`${TT_API_BASE}/Access/Login`, { username: username, password: password, applicationId: 2 }, {
headers: {
'Content-Type': 'application/json;charset=utf-8',
'Authorization': 'Basic ' + auth,
}
})
return onSuccess(req.data)
}
catch (err) {
return onError(err)
}
}
}