【问题标题】:How to call promise function in reducer?如何在reducer中调用promise函数?
【发布时间】:2016-05-28 04:53:10
【问题描述】:

我在 reducer 中调用了一个 promise 函数,所以我这样称呼它:

cart(state, action) {
    switch(action.type) {
    //...
    case LOG_IN:
        return getCartProducts(true)
    }
}


getCartProducts(isLogin) {
    // ....
    return cartApi.list({
            customerId: "",
            items: items
        }).then(data => {
            return cartReduce(undefined, receiveCartProducts(data.items, false))
        })
}

所以这只是返回一个承诺,而不是我想要的对象

【问题讨论】:

  • reducer 应该是纯的,你不应该在那里请求东西。
  • @QoP 所以如果我想听LOG_IN 的动作,我该怎么办?
  • 看看 redux-thunk 作为管理异步请求的一种可能机制。您基本上会触发多个操作来表示异步请求状态。也强烈推荐你阅读官方的 redux 文档。

标签: reactjs promise redux reducers


【解决方案1】:

您应该按照in the Redux docs 的描述对这些进行异步操作。

import fetch from 'isomorphic-fetch';

// One action to tell your app you're fetching data
export const GET_CART_PRODUCTS_REQUEST = 'GET_CART_PRODUCTS_REQUEST'
function getCartProductsRequest(customerId) {
  return {
    type: GET_CART_PRODUCTS_REQUEST,
    customerId
  };
}

// One action to signify success
export const GET_CART_PRODUCTS_SUCCESS = 'GET_CART_PRODUCTS_SUCCESS'
function getCartProductsSuccess(cartProducts) {
  return {
    type: GET_CART_PRODUCTS_SUCCESS,
    cartProducts
  };
};

// One action to signify an error
export const GET_CART_PRODUCTS_ERROR = 'GET_CART_PRODUCTS_ERROR'
function getCartProductsSuccess(error) {
  return {
    type: GET_CART_PRODUCTS_ERROR,
    error
  };
};

// This is the async action that fires one action when it starts
// And then one of two actions when it finishes
export function fetchCartProducts(customerId) {
  return dispatch => {
    // Dispatch action that tells your app you're going to get data
    // This is where you'll set any 'isLoading' state in your store
    dispatch(getCartProductsRequest(customerId))

    return fetch('https://api.website.com/customers/' + customerId + '/cartProducts')
      .then(response => response.json())
      .then(
        // Fire success action on success
        cartProducts => dispatch(getCartProductsSuccess(cartProducts)),

        // Fire error action on error
        error => dispatch(getCartProductsError(error))
      );
    };
  };
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-26
    • 1970-01-01
    • 1970-01-01
    • 2018-05-23
    相关资源
    最近更新 更多