如果使用Array.prototype.splice方法有效,那么看起来您正在调度removeBook
并传递一个索引作为有效负载值.
removeBook(state, action) {
state.books.splice(action.payload, 1);
}
{books.map((book, index) => (
<div key={book.title}>
<h2>{book.title}</h2>
<button
type="button"
onClick={() => dispatch(removeBook(index))} // <-- passing index
>
X
</button>
</div>
)}
如果要使用索引和筛选器:
removeBook(state, action) {
state.books = state.books.filter((book, index) => index !== action.payload);
}
{books.map((book, index) => (
<div key={book.title}>
<h2>{book.title}</h2>
<button
type="button"
onClick={() => dispatch(removeBook(index))} // <-- passing index
>
X
</button>
</div>
)}
如果您想使用书名从状态中删除一本书,则传递该书的书名值.
removeBook(state, action) {
state.books = state.books.filter(book => book.title !== action.payload);
}
{books.map((book) => (
<div key={book.title}>
<h2>{book.title}</h2>
<button
type="button"
onClick={() => dispatch(removeBook(book.title))} // <-- passing title
>
X
</button>
</div>
)}