React Redux传递到Reducer的未定义对象



我正在用typescript开发我的第一个React Redux应用程序,我有一个特殊的错误,即reducer接收的对象是"未定义的"。

类型.ts

//Action types
export const ADD_FAVOURITE = 'ADD_FAVOURITE'
export const REMOVE_FAVOURITE = 'REMOVE_FAVOURITE'
//Add favourite action
interface addFavouriteAction {
type: typeof ADD_FAVOURITE,
favourite: ImageThumbnail
}
//Remove favourite action
interface removeFavouriteAction {
type: typeof REMOVE_FAVOURITE,
id: string
}
export type favouriteActionTypes = addFavouriteAction | removeFavouriteAction
export interface favouriteState {
favourites: ImageThumbnail[]
}
export const initialState: favouriteState = {
favourites: []
}
export type rootState = ReturnType<typeof favouriteReducer>

store.ts

export const rootReducer = combineReducers({
favouriteReducer
})
const store = createStore(rootReducer)
export default store

操作.ts

export function addFavourite (image: ImageThumbnail): favouriteActionTypes {
return {
type: ADD_FAVOURITE,
favourite: image
}
}
export function removeFavourite (id: string): favouriteActionTypes {
return {
type: REMOVE_FAVOURITE,
id: id
}
}

减速器.ts

export function favouriteReducer(
state = initialState,
action: favouriteActionTypes
): favouriteState {
switch (action.type) {
case ADD_FAVOURITE:
console.log(`am here in add fav object is: ${action.favourite}`)
return {
favourites: [...state.favourites, action.favourite]
}
case REMOVE_FAVOURITE:
return {
favourites: state.favourites.filter(
favourite => favourite.id !== action.id
)
}
default:
return state
}
}

reducer中的console.log总是返回一个未定义的对象。

使用按钮调用这些操作的组件如下所示。this.props.imageThumbnail是一个有效的对象,它被传递到addFavourite/removeFavourite函数中。

组件.tsx

const mapState = (state: rootState) => ({
favourites: state.favourites
})
const mapDispatch = {
addFavourite: (image: ImageThumbnail) => ({ type: 'ADD_FAVOURITE' }),
removeFavourite: (id: string) => ({ type: 'REMOVE_FAVOURITE' })
}
//component declaration
//render method
<TouchableOpacity
onPress={() => this.props.addFavourite(this.props.imageThumbnail)}
/>
<TouchableOpacity
onPress={() => this.props.removeFavourite(this.props.imageThumbnail.id)}
/>
const connector = connect(
mapState,
mapDispatch
)
type PropsFromRedux = ConnectedProps<typeof connector>
export default connector(component)

您没有将图像传递给操作。这应该是:

addFavourite: (image: ImageThumbnail) => ({ type: 'ADD_FAVOURITE', favourite: image }),

问题出在组件.tsx中。您所做的映射应该是这样的:

const mapDispatchToProps = (dispatch) => {
return {
addFavourite: (image: ImageThumbnail) => (dispatch(addFavourite(image)),
removeFavourite: (id: string) => (dispatch(removeFavourite(id))
};
};

以便您提供的数据将被提供给操作。addFavorite和removeFavorite也应该从您的actions.ts.中导入

相关内容

  • 没有找到相关文章

最新更新