使用 redux-thunk 时如何在 ActionCreator 中实例化回调?

How to instantiate a callback in an ActionCreator when using redux-thunk?

在下面的代码中,'callback' 参数是我的组件中调用动作创建器的函数,但是我似乎无法确定在我的动作创建器中调用此回调的位置。我正在使用 ReduxThunk 实现异步功能。

我的主要objective是在请求成功后触发回调。

import axios from 'axios';
export const FETCH_USERS = 'FETCH_USERS';
const API_URL_TOP30 = 'https://fcctop100.herokuapp.com/api/fccusers/top/recent';
const API_URL_ALLTIME = 'https://fcctop100.herokuapp.com/api/fccusers/top/alltime';

export function fetchUsers(list, callback) {
  const apicall = (list) ? API_URL_ALLTIME : API_URL_TOP30
  const data = ''
  const request = axios.get(apicall)

  return (dispatch) => {
    request.then(({data}) => {
      dispatch({ type: FETCH_USERS, payload: data })
    })
  }
}

then方法中调用回调

export function fetchUsers(list, callback) {
    const apicall = (list) ? API_URL_ALLTIME : API_URL_TOP30
    const data = ''
    const request = axios.get(apicall)

    return (dispatch) => {
        request.then(({ data }) => {
            callback(data);
            dispatch({ type: FETCH_USERS, payload: data })
        })
    }
}

无需将回调作为第二个参数传递给您的函数,您可以 return 您对该函数的承诺。

 export function fetchUsers(list) {
  const apicall = (list) ? API_URL_ALLTIME : API_URL_TOP30
  const data = ''
  const request = axios.get(apicall)

  return (dispatch) => {
   return request.then(({data}) => {
    dispatch({ type: FETCH_USERS, payload: data })
   })
  }
}

这使得您可以在您的组件中使用 .then(),因为您的函数 return 是一个承诺。

*** Your component ***
fetchUsers(list).then(() => { 
 console.log('success')
})