TypeError: undefined is not an object (evaluating 'state.favoriteBooks.findIndex')
TypeError: undefined is not an object (evaluating 'state.favoriteBooks.findIndex')
每次我按收藏夹按钮时都会出现错误。
TypeError: undefined is not an object (evaluating 'state.favoriteBooks.findIndex')
这个错误发生在book.js redux 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。
在SET_BOOKS
return我忘了加..state
。
...
case SET_BOOKS:
return {
...state,
books: action.books,
};
...
不要忘记添加 ...state
,因为您想在 initialState
中保存以前的状态。这就是为什么它没有在 books
.
中获取任何 ID
每次我按收藏夹按钮时都会出现错误。
TypeError: undefined is not an object (evaluating 'state.favoriteBooks.findIndex')
这个错误发生在book.js redux 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。
在SET_BOOKS
return我忘了加..state
。
...
case SET_BOOKS:
return {
...state,
books: action.books,
};
...
不要忘记添加 ...state
,因为您想在 initialState
中保存以前的状态。这就是为什么它没有在 books
.