更新:问题直接在reducer中,与onClick函数和deleteLastItem函数无关。我用console.logs对此进行了测试,显然唯一重复两次的是直接在reducer中的那个。
我同时测试了钩子 useReducer 和 useContext ,因为我认为它们可以很好地协同工作,但显然,当我将一个函数设置为 onClick 函数时,它会被触发两次,而且它不是因为我'正在删除数组中的最后一项,因此它删除了两项而不是一项。
这是存储上下文和 reducer 挂钩的文件:
import React, {createContext, useReducer} from "react";
const initialState = {
books: [
{name: "Book 8", autor: "Author 8", id: 8},
{name: "Book 7", autor: "Author 7", id: 7},
{name: "Book 6", autor: "Author 6", id: 6},
{name: "Book 5", autor: "Author 5", id: 5},
{name: "Book 4", autor: "Author 4", id: 4},
{name: "Book 3", autor: "Author 3", id: 3}
]
}
const reducer = (state, action) => {
switch (action.type) {
case "DELETE":
state.books.pop();
console.log("hey");
return {...state}
default:
return {...state}
}
}
export const BookContext = createContext();
export const BookProvider = props => {
const [state, dispatch] = useReducer(reducer, initialState);
// Actions
const deleteLastBook = () => dispatch({type: "DELETE"});
return (
<BookContext.Provider value={{books: state.books, deleteLastBook}}>
{props.children}
</BookContext.Provider>
)
}
如您所见,console.log("hey")
, 告诉我它被执行了两次(除了看到屏幕中的项目一次被清除两次)
这是引入上下文以及出现问题的组件:
import React, {useContext} from 'react';
import {BookContext} from "../context/BookContext";
const Books = () => {
const information = useContext(BookContext);
const {books, deleteLastBook} = information;
const deleteBook = e => {
e.preventDefault();
deleteLastBook();
};
return (
<div>
{console.log(books)}
{books.map(book => (<h1 key={book.id}>{book.name}</h1>))}
<button onClick={deleteBook}>Delete book</button>
</div>
)
}
export default Books;
最后,这里是 app.js,我认为它没有用,但以防万一:
import React from 'react';
import './App.css';
import {BookProvider} from "./context/BookContext";
import Books from "./components/Books";
const App = () => {
return (
<BookProvider>
<div className="App">
<Books />
</div>
</BookProvider>
);
}
export default App;