【问题标题】:Importing redux actions from other files to compose redux-thunks (using Ducks)从其他文件导入 redux 操作以组成 redux-thunk(使用 Ducks)
【发布时间】:2017-10-22 17:28:42
【问题描述】:

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

【问题讨论】:

    标签: redux redux-thunk


    【解决方案1】:

    你应该总是返回promise,在你的情况下问题是dispatch不返回promise,试试下面的代码

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

    【讨论】:

      猜你喜欢
      • 2018-03-20
      • 2018-01-31
      • 2019-03-23
      • 2017-10-14
      • 2016-08-06
      • 2018-09-07
      • 2018-09-22
      • 1970-01-01
      • 2017-03-03
      相关资源
      最近更新 更多