从其他文件导入 redux 操作以组成 redux-thunks(使用 Ducks)

Importing redux actions from other files to compose redux-thunks (using Ducks)

我一直在使用 Ducks pattern 构建我的 redux 包,到目前为止它运行良好。但是,我还没有完全弄清楚的一个用例是我应该如何编写从多个不同文件调度操作的 thunk。

例如,我有一个 redux 包文件,看起来像

// redux/geo.js

const NAME = 'myapp/geo'
const POSITION_CHANGE = `${NAME}/POSITION_CHANGE`

const initialState = {
  position: {},
}

export default function reducer(state = initialState, action = {}) {
  switch (action.type) {
    case POSITION_CHANGE:
      return {
        ...state,
        position: action.value
      }
    default:
      return state
  }
}

export function getPositionAsync() {
  return new Promise(function(resolve, reject) {
    navigator.geolocation.getCurrentPosition(
      (position) => resolve(position),
      (error) => reject(error),
    )
  })
}

export function positionChange(value) {
  return {type: POSITION_CHANGE, value}
}

还有一个

// redux/search.js

import {getPositionAsync, positionChange} from './geo.js' // doesn't seem to work... do I need to import something else?

const NAME = 'myapp/search'
const RESULTS_SHOW = `${NAME}/RESULTS_SHOW`

const initialState = {
  showResults: false,
}

export default function reducer(state = initialState, action = {}) {
  switch (action.type) {
    case RESULTS_SHOW:
      return {
        ...state,
        showResults: action.value,
      }
    default:
      return state
  }
}

export function resultsShow(value) {
  return {type: RESULTS_SHOW, value}
}

// thunk that is composed of actions from geo.js and search.js
export function executeSearch() {
  return dispatch => getPositionAsync()
    .then(position => dispatch(positionChange(position)))
    .then(() => dispatch(resultsShow(true)))
}

但是当我尝试发送 executeSearch thunk 时,这给了我一个错误。我做错了什么?

你应该总是return承诺,在你的情况下问题是调度不return承诺,试试下面的代码

export function executeSearch() {
  return dispatch => getPositionAsync()
     .then(position => {
          dispatch(positionChange(position));
          dispatch(resultsShow(true))
     })
 }