在使用redux的状态下未正常修改值时



当点击like按钮时,我想将like-of-book设置为true,然后将其放入一个名为likedBook的变量中。

但现在在我的代码中,它并没有立即添加。

case ADD_TO_LIST :
return {
...state,
books: state.books.concat({
title: action.item.title,
contents: action.item.contents,
thumbnail: action.item.thumbnail,
liked: false
}),
};
case LIKED :
return {
...state,
books : state.books.map((book) => book.title === action.item.title ? {...book, liked: true} : book),
likedBook : state.books.filter(((book)=> book.liked === true))
}

export interface Book{
title : String, 
contents: String,
thumbnail: String,
liked: boolean
}
const initialState : {books: Book[]; likedBook: Book[];}= {
books : [],
likedBook: []
};

在此处输入图像描述

点赞是真的,但它不会添加到点赞簿中。我的代码出了什么问题?我该如何修复它?

我将首先搜索书籍,然后通过title切换like属性,并将整个书籍添加到likedBook数组中。

case LIKED :
// search if book already in state to like
const book = state.book.find(book => book.title === action.item.title);
// book found
if (book) {
// create new liked book object
const likedBook = { ...book, liked: true };
return {
...state,
// map to new books array, add new liked book or existing book
books: state.books.map((book) => book.title === action.item.title
? likedBook
: book
),
// append to new likedBook array
likedBook : state.likedBook.concat(likedBook),
}
}
// book not found, return current state
return state;

在case LIKED的return语句中,它不是逐行执行的。

像这样修改代码。

case LIKED :
return {
...state,
books : state.books.map((book) => book.title === action.item.title ? {...book, liked: true} : book),
likedBook : [...state.likedBook, state.books.find(book => book.title === action.item.title)]
}

相关内容

  • 没有找到相关文章

最新更新