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

时间:2017-10-22 17:28:42

标签: redux redux-thunk

我使用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时,这会给我一个错误。我做错了什么?

1 个答案:

答案 0 :(得分:3)

你应该总是回复承诺,在你的情况下,问题是发送不返回承诺,试试下面的代码

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