[英]response undefined using then for async redux api call?
如何在Redux中使用api調用的響應正確重定向用戶? 我需要axios之后的響應,但是我不確定,盡管我在動作中返回了thunk
//jobForm.js
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { createJob } from '~/actions/jobAction'
import { getUserId } from '~/utils'
import moment from 'moment'
@connect(state=>state.job,{createJob})
class Form extends Component {
handleSubmitForm = () => {
this.props.createJob({formData})
.then(resp => console.log(resp)) //undefined?)
}
//etc..
}
export default Form
//action
export function createJob(params) {
return dispatch=>{
dispatch({type: CREATING_JOB})
return axios.post(`/job/create`, {...params})
.then(res=>{
if(res.status===200 && res.data.status===1){
dispatch({
type: CREATE_JOB,
payload: res.data.data
})
}
})
.catch(res => {
dispatch(errorMsg(res.data.msg))
})
}
}
我可以將有效負載傳遞給reducer,但是我需要一個響應的ID將用戶重定向到創建的作業頁面。
處理完API調用后,您不會返回任何信息,這就是Promise解析為“ undefined”的原因。 為了保證用數據解決問題,您需要在分派操作后返回ID。 見下文。
export function createJob(params) {
return dispatch=>{
dispatch({type: CREATING_JOB})
return axios.post(`/job/create`, {...params})
.then(res=>{
if(res.status===200 && res.data.status===1){
dispatch({
type: CREATE_JOB,
payload: res.data.data
});
// RETURN ID AFTER DISPATCHING ACTION
return res.data.data
}
})
.catch(res => {
dispatch(errorMsg(res.data.msg))
})
}
}
可以說與通量單向數據流范式更內聯的另一種方法是基於redux狀態的更改而不是完成操作來執行重定向。
您可以使用componentWillReceiveProps來確定是否已創建新作業,如果是,則重定向
componentWillReceiveProps(nextProps) {
// use nextProps to determine if the new job has been added
// to the job state
// ...
const isNewJobAdded = nextProps.job.includes(...)
if (isNewJobAdded) {
// perform redirect
...
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.