我在列react 待办事项 list . 它的Find工作没有任何错误.
然而,当我进入列表时,它不会出现(它只在我点击页面时出现). 我试图更改handleSubmit函数,但仍然无法弄清楚.我怎么才能修好它呢?
这是我的代码.它具有分页功能,每5个列表,并移动到下一页.
import React, { useState, useEffect } from "react";
import "./App.css";
export default function App() {
const [todoData, setTodoData] = useState([]);
const [value, setValue] = useState("");
const [currentPage, setCurrentPage] = useState(1);
const [currentTodos, setCurrentTodos] = useState([]);
const todosPerPage = 5;
const btnStyle = {
color: "#fff",
border: "none",
padding: "5px 9px",
borderRadius: "50%",
cursor: "pointer",
float: "right",
};
const getStyle = (finished) => {
return {
padding: "10px",
borderBottom: "1px #ccc dotted",
textDecoration: finished ? "line-through" : "none",
};
};
const handleClick = (id) => {
let newTodoData = todoData.filter((data) => data.id !== id);
setTodoData(newTodoData);
};
const handleChange = (e) => {
setValue(e.target.value);
};
const handleSubmit = (e) => {
e.preventDefault();
let newTodo = {
id: Date.now(),
title: value,
finished: false,
};
setTodoData((prev) => [...prev, newTodo]);
if ((todoData.length + 1) % todosPerPage === 1) {
setCurrentPage((prevPage) => prevPage + 1);
}
setValue("");
};
const handleFinished = (id) => {
let newTodoData = todoData.map((data) => {
if (data.id === id) {
data.finished = !data.finished;
}
return data;
});
setTodoData(newTodoData);
};
useEffect(() => {
const indexOfLastTodo = currentPage * todosPerPage;
const indexOfFirstTodo = indexOfLastTodo - todosPerPage;
const currentTodos = todoData
.filter(
(_, index) => index >= indexOfFirstTodo && index < indexOfLastTodo
)
.slice(0, todosPerPage);
setCurrentTodos(currentTodos);
}, [todoData, currentPage, todosPerPage]);
return (
<div className="container">
<div className="todoBlock">
<div className="title">
<h1 className="title" style={{ textAlign: "center" }}>
Todo List
</h1>
</div>
{currentTodos.map((data) => (
<div style={getStyle(data.finished)} key={data.id}>
<input
type="checkbox"
onChange={() => handleFinished(data.id)}
defaultChecked={false}
/>
{data.title}
<button style={btnStyle} onClick={() => handleClick(data.id)}>
x
</button>
</div>
))}
<form style={{ display: "flex" }} onSubmit={handleSubmit}>
<input
type="text"
name="value"
style={{ flex: "10", padding: "5px" }}
placeholder="Here"
value={value}
onChange={handleChange}
/>
<button className="btn" type="submit" style={{ flext: "1" }}>
Enter
</button>
</form>
<div className="pagination">
{Array.from(
{ length: Math.ceil(todoData.length / 5) },
(_, i) => i + 1
).map((pageNumber) => (
<button
key={pageNumber}
onClick={() => setCurrentPage(pageNumber)}
className={currentPage === pageNumber ? "active" : ""}
>
{pageNumber}
</button>
))}
</div>
</div>
</div>
);
}
谢谢!