【问题标题】:TypeError: undefined is not an object (evaluating 'state.favoriteBooks.findIndex')TypeError: undefined is not an object (evaluating \'state.favoriteBooks.findIndex\')
【发布时间】:2022-12-21 11:58:28
【问题描述】:

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

TypeError: undefined is not an object  (evaluating 'state.favoriteBooks.findIndex')

此错误发生在书.js还原减速器:

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。

【问题讨论】:

    标签: react-native redux react-redux expo


    【解决方案1】:

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

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

    不要忘记添加...state,因为你想在initialState中保存以前的状态。这就是为什么它没有在books 中获取任何 ID。

    【讨论】:

      猜你喜欢
      • 2023-02-18
      • 2022-12-03
      • 2019-11-02
      • 2020-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-19
      • 1970-01-01
      相关资源
      最近更新 更多