简体   繁体   English

响应未定义,然后用于异步redux api调用?

[英]response undefined using then for async redux api call?

How to properly redirect user using the response of the api call in redux? 如何在Redux中使用api调用的响应正确重定向用户? I need the resp after axios's then but I got undefined, although I've returned the thunk in my action 我需要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))
    })
  }
}

I can pass my payload to reducer but I need a response's id to redirect the user to a created job page. 我可以将有效负载传递给reducer,但是我需要一个响应的ID将用户重定向到创建的作业页面。

You're not returning anything after processing the API call, which is why the promise resolves to "undefined". 处理完API调用后,您不会返回任何信息,这就是Promise解析为“ undefined”的原因。 For the promise to resolve with data, you'll need to return the id after dispatching the action. 为了保证用数据解决问题,您需要在分派操作后返回ID。 See below. 见下文。

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))
    })
  }
}

An alternative approach, that is arguably more inline with the flux one-way data flow paradigm would be to perform the redirect based on a change in the redux state rather than completion of the action. 可以说与通量单向数据流范式更内联的另一种方法是基于redux状态的更改而不是完成操作来执行重定向。

You could use componentWillReceiveProps to determine if the new job has been created, if so, redirect 您可以使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM