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
相关产品推荐
相关产品推荐

