react.js - 多个fetch异步调用,不能拿到调用之后的值

查看:284
本文介绍了react.js - 多个fetch异步调用,不能拿到调用之后的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

export const editCase = () => (dispatch, getState) => {
  let caseObject = jquery.extend(true, {}, getState().caseDetail.caseObject)
  let platforms = getPlatforms()
  let countries = getCountries()
  dispatch(initializeCreator(caseObject, platforms, countries, true))
}

执行dispatch函数的时候,此时platforms,countries还没有拿到值

const initializeCreator = (caseObject, platforms, countries, isEdit) => ({
  type: types.EDIT_CASE,
  caseObject,
  platforms,
  countries,
  isEdit
})

const getPlatforms = () => {
  fetch(constants.FETCH_URL + '/platforms', {
    mode: 'cors',
    method: 'GET',
    cache: 'default',
    credentials: 'include'
    })
    .then(response => response.json())
    .then(platforms => {
      return platforms
    })
}

const getCountries = () => {
  fetch(constants.FETCH_URL + '/region/countryList', {
    mode: 'cors',
    method: 'GET',
    cache: 'default',
    credentials: 'include'
    })
    .then(response => response.json())
    .then(countryNames => {
      let countryOptions = []
      countryNames.map((countryName, index) => {
        countryOptions.push(<option value={index} key={index}>{countryName}</option>)
      })
      return {
        countryNames,
        countryOptions
      }
    })
}

解决方案

下面的getLocation就等同于上面的getCountries,和getPlatforms的写法差不多,getLocation里面的getCountries,getProvinces和getCities都可以不用管,只需知道这种写法就行.
fetch用的是import fetch from 'isomorphic-fetch'

export const editCase = () => (dispatch, getState) => {
  let caseObject = jquery.extend(true, {}, getState().caseDetail.caseObject)
  let data = {}
  getPlatforms()
  .then(platforms => {
    data.platforms = platforms
    return getLocation(countryId, provinceId)
  })
  .then(location => {
    data.location = location
    dispatch(initializeCreator(caseObject, data.platforms, data.location))
  })
}

export const getPlatforms = () => {
  return fetch(constants.FETCH_URL + '/platforms', {
    mode: 'cors',
    method: 'GET',
    cache: 'default',
    credentials: 'include'
    })
    .then(response => response.json())
    .then(platforms => {
      return platforms
    })
}

export const getLocation = (countryId, provinceId) => {
  let location = {}
  return getCountries()
         .then(countries => {
           location.countries = countries
           return getProvinces(countryId)
          })
         .then(provinces => {
           location.provinces = provinces
           return getCities(countryId, provinceId)
          })
         .then(cities => {
           location.cities = cities
           return location
         })
}

const initializeCreator = (caseObject, platforms, location) => ({
  type: types.EDIT_CASE,
  caseObject,
  platforms,
  location
})

这篇关于react.js - 多个fetch异步调用,不能拿到调用之后的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆