React – 输入数据已添加但不显示

huangapple go评论58阅读模式
英文:

React - input data added but doesn't display

问题

I am making React todo List.
it works fine without any errors.

However, when I enter the list, it doesn't appear (it appears only when I click the page).
I tried to change the handleSubmit function but still can't figure it out. How can I fix it?

Here is my code. it has pagination function for every 5 lists and moves to the next page.

英文:

I am making React todo List.
it works find without any error.

However, when I enter the list, it doesn't appear (it appears only when I click the page).
I tried to change the handleSubmit function but still can't figure it out. How can I fix it?

Here is my code. it has pagination function for every 5 lists, and move to next page.

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>
  );
}

Thank you!

答案1

得分: 0

const [currentPage, setCurrentPage] = useState(0);

将页面的默认值设置为0

这个修改可以。

useEffect(() => {
    const indexOfLastTodo = currentPage * todosPerPage;
    const indexOfFirstTodo = indexOfLastTodo - todosPerPage;
    console.log('todoData:', todoData);
    console.log(indexOfLastTodo, indexOfFirstTodo);
    const currentTodos = todoData
      .slice(indexOfFirstTodo, indexOfLastTodo);
    console.log(currentTodos);
    setCurrentTodos(currentTodos);
}, [todoData, currentPage]);

多次记录将显示问题。

英文:
const [currentPage, setCurrentPage] = useState(0);

Set the default value of the page to 0

This modification is okay.

useEffect(() => {
    const indexOfLastTodo = currentPage * todosPerPage;
    const indexOfFirstTodo = indexOfLastTodo - todosPerPage;
    console.log('todoData:',todoData)
 console.log(indexOfLastTodo,indexOfFirstTodo)
    const currentTodos = todoData
      .slice(indexOfFirstTodo,indexOfLastTodo)
      console.log(currentTodos);
      setCurrentTodos(currentTodos);

  }, [todoData, currentPage]);

Multiple logs will reveal problems

huangapple
  • 本文由 发表于 2023年4月17日 08:56:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76031060.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定