redux TypeError:undefined不是对象(正在评估“state.favoriteBooks. findIndex”)

pcrecxhr  于 2022-12-23  发布在  其他
关注(0)|答案(1)|浏览(132)

每次我按下收藏夹按钮,它都给我一个错误。

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。

h9vpoimq

h9vpoimq1#

SET_BOOKS返回时,我忘记添加...state

...
    case SET_BOOKS:
  return {
    ...state,
    books: action.books,
  };
...

别忘了添加...state,因为你想把以前的状态保存在initialState中,这就是为什么它没有在books中拾取任何id。

相关问题