You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native集成Redux报错:Undefined is not an object (evaluating 'action.type')

问题解决方案

嘿,我一眼就发现问题出在哪了!

错误根源

在你的favoriteReducer.js文件最后一行,你导出的是执行后的reducer函数结果,而不是reducer函数本身:

export default toggleFavorite()

这行代码会立刻调用toggleFavorite函数,返回的是初始状态对象{ favoriteQuotes: [] },但Redux的createStore需要接收的是一个reducer函数(也就是那个能接收state和action参数的函数),而不是一个状态对象。

当你把这个状态对象传给createStore后,Redux在处理dispatch的动作时,会错误地把这个对象当作函数去调用,这时候action参数根本没有被正确传入,自然就会抛出undefined is not an object(evaluating 'action.type')的错误。

修复步骤

只需要修改favoriteReducer.js的导出语句,去掉后面的括号即可:

export default toggleFavorite

这样configureStore.js里导入的就是真正的reducer函数,createStore就能正常初始化store,当你dispatchTOGGLE_FAVORITE动作时,reducer会正确接收到action参数,switch语句也能正常判断action.type了。

额外小建议

为了代码更规范,你可以用const来定义reducer函数,可读性会更好:

const initialState = { favoriteQuotes: [] }
const toggleFavorite = (state = initialState, action) => {
  let nextState
  switch (action.type) {
    case 'TOGGLE_FAVORITE':
      const favoriteQuoteIndex = state.favoriteQuotes.findIndex(item => item.id === action.value.id)
      if (favoriteQuoteIndex !== -1) {
        nextState = { ...state, favoriteQuotes: state.favoriteQuotes.filter( (item, index) => index !== favoriteQuoteIndex) }
      } else {
        nextState = { ...state, favoriteQuotes: [...state.favoriteQuotes, action.value] }
      }
      return nextState || state
    default:
      return state
  }
}
export default toggleFavorite

内容的提问来源于stack exchange,提问作者Ben D

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 09:22:08