每次我按下收藏夹按钮,它都给我一个错误。
TypeError: undefined is not an object (evaluating 'state.favoriteBooks.findIndex')
此错误发生在book.jsredux reducer中:
import { SET_BOOKS, TOGGLE_FAVORITE } from '../actions/types';
import Book from '../../models/book';
const initialState = {
books: [],
favoriteBooks: [],
};
export default (state = initialState, action) => {
switch (action.type) {
case SET_BOOKS:
return {
books: action.books,
};
case TOGGLE_FAVORITE:
const existingIndex = state.favoriteBooks.findIndex(
(book) => book.id === action.bookId
);
if (existingIndex >= 0) {
const updatedFavBooks = [...state.favoriteBooks];
updatedFavBooks.splice(existingIndex, 1);
return { ...state, favoriteBooks: updatedFavBooks };
} else {
const book = state.books.find((book) => book.id === action.bookId);
return { ...state, favoriteBooks: state.favoriteBooks.concat(book) };
}
default:
return state;
}
};
我认为问题在于当变量为空时,它试图找到索引,但当我运行调度**toggleFavorite(BookId)**时,它输入了图书ID。
1条答案
按热度按时间h9vpoimq1#
在
SET_BOOKS
返回时,我忘记添加...state
。别忘了添加
...state
,因为你想把以前的状态保存在initialState
中,这就是为什么它没有在books
中拾取任何id。