异步操作创建者未按预期调度操作

时间:2017-04-11 04:01:53

标签: ecmascript-6 redux redux-mock-store

人。

我有以下异步操作创建者,根据当前状态调度另一个操作创建者或返回null。问题是,无论目前的状态是什么,它总是会返回null

// actions.js

export const loadPosts = category => (dispatch, getState) => {
  const currentState = getState()
  const posts = currentState.postsByCategory
  const categoryPosts = posts[category]
  const items = categoryPosts.items

  if(items === []) {
    return dispatch(fetchPosts(category))
  }

  return null
}

如您所见,动作创建者调度fetchPosts()取决于items的值等于空数组。我正在测试它,为它提供一个具有以下结构的初始状态:

// initialState
const initialState = {
  postsByCategory: {
    hot: {
      isFetching: false,
      items: []
    }
  }
}

我显然没有正确访问items属性,但我无法看到代码中的错误在哪里。 我正在使用redux-mock-store测试它,创建一个mockStore实例,并为其提供initialState。 希望你们能够在我的代码中查明错误。 提前谢谢。

1 个答案:

答案 0 :(得分:3)

您的问题出在comparison

if(items === [])

在上面的代码中,项目不是===[],因为它们都是不同的实例。如果您想检查items是否为空,请使用items.length === 0。希望有所帮助。