如何在React中使用useParams()时在页面之间传递数据?

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

How to pass data between pages in react when using useparams()?

问题

App.jsx

import './App.css'
import React, {useState} from 'react';
import { Link, Routes, Route } from 'react-router-dom';
import Calendar from "./components/calendar/calendar.jsx";
import ToDo from "./components/todolist/todolist.jsx";
import { useParams } from 'react-router-dom';

const App = () => {

    return (
        <div>
            <Routes>
                <Route path='/' element={<Calendar  />} />
                <Route path='/todo/:id' element={<ToDo />} />
            </Routes>
        </div>
    )
}

export default App;

calendar.jsx

import './calendar.css';
import {Link} from 'react-router-dom'
import React from "react";

const Calendar = () => {

    return (
        <div className="month">
            <h1> February 2023 </h1>
            <div className="names">
                <div className="weekNames">Monday</div>
                <div className="weekNames">Tuesday</div>
                <div className="weekNames">Wednesday</div>
                <div className="weekNames">Thursday</div>
                <div className="weekNames">Friday</div>
                <div className="weekNames">Saturday</div>
                <div className="weekNames">Sunday</div>
            </div>
            <div className="week">
                <div className="day">1 <Link to='/todo/1'> To-Do:  </Link> </div>
                <div className="day">2 <Link to='/todo/2'> To-Do:  </Link> </div>
                <div className="day">3 <Link to='/todo/3'> To-Do: </Link> </div>
                <div className="day">4 <Link to='/todo/4'> To-Do: </Link> </div>
                <div className="day">5 <Link to='/todo/5'> To-Do: </Link> </div>
                <div className="day">6 <Link to='/todo/6'> To-Do: </Link> </div>
                <div className="day">7 <Link to='/todo/7'> To-Do: </Link> </div>
                <div className="day">8 <Link to='/todo/8'> To-Do: </Link></div>
                <div className="day">9 <Link to='/todo/9'> To-Do: </Link> </div>
                <div className="day">10 <Link to='/todo/10'> To-Do: </Link> </div>
                <div className="day">11 <Link to='/todo/11'> To-Do: </Link> </div>
                <div className="day">12 <Link to='/todo/12'> To-Do: </Link> </div>
                <div className="day">13 <Link to='/todo/13'> To-Do: </Link> </div>
                <div className="day">14 <Link to='/todo/14'> To-Do: </Link> </div>
                <div className="day">15 <Link to='/todo/15'> To-Do: </Link> </div>
                <div className="day">16 <Link to='/todo/16'> To-Do: </Link> </div>
                <div className="day">17 <Link to='/todo/17'> To-Do: </Link> </div>
                <div className="day">18 <Link to='/todo/18'> To-Do: </Link> </div>
                <div className="day">19 <Link to='/todo/19'> To-Do: </Link> </div>
                <div className="day">20 <Link to='/todo/20'> To-Do: </Link> </div>
                <div className="day">21 <Link to='/todo/21'> To-Do: </Link> </div>
                <div className="day">22 <Link to='/todo/22'> To-Do: </Link> </div>
                <div className="day">23 <Link to='/todo/23'> To-Do: </Link> </div>
                <div className="day">24 <Link to='/todo/24'> To-Do: </Link> </div>
                <div className="day">25 <Link to='/todo/25'> To-Do: </Link> </div>
                <div className="day">26 <Link to='/todo/26'> To-Do: </Link> </div>
                <div className="day">27 <Link to='/todo/27'> To-Do: </Link> </div>
                <div className="day">28 <Link to='/todo/28'> To-Do: </Link> </div>
            </div>
        </div>
    );
}

export default Calendar

todolist.jsx

import './todolist.css';
import React from "react";
import { NavLink } from "react-router-dom";
import { useParams } from 'react-router-dom';

const ToDo = () => {
  const {id} = useParams()
  const [todos, setTodos] = React.useState(() => JSON.parse(localStorage.getItem(`todos-${id}`)) || []);
  const [todo, setTodo] = React.useState("");
  const [todoEditing, setTodoEditing] = React.useState(null);
  const [editingText, setEditingText] = React.useState("");

  React.useEffect(() => {
    const json = JSON.stringify(todos);
    localStorage.setItem(`todos-${id}`, json);
  }, [todos, id]);

  function handleSubmit(e) {
    e.preventDefault();
    const newTodo = {
      id: new Date().getTime(),
      text: todo,
      completed: false,
    };
    setTodos([...todos].concat(newTodo));
    setTodo("");
  }

  function deleteTodo(id) {
    let updatedTodos = [...todos].filter((todo) => todo.id !== id);
    setTodos(updatedTodos);
  }

  function toggleComplete(id) {
    let updatedTodos = [...todos].map((todo) => {
      if (todo.id === id) {
        todo.completed = !todo.completed;
      }
      return todo;
    });
    setTodos(updatedTodos);
  }

  function submitEdits(id) {
    const updatedTodos = [...todos].map((todo) => {
      if (todo.id === id) {
        todo.text = editingText;
      }
      return todo;
    });
    setTodos(updatedTodos);
    setTodoEditing(null);
  }

  return (
    <div>
      <div align='right'>
        <NavLink to='/' style={{textDecoration: 'none', color: 'black'}}><button className='btn'> Calendar View </button></NavLink>
      </div>
      <div id="todo-list">
        <h1>To-Do For Today</h1>
        <h2> Total Tasks: {todos.length} </h2>
        <form onSubmit={handleSubmit}>
          <input
            type="text"
            onChange={(e) => setTodo(e.target.value)}
            value={todo}
          />
          <button className="btn">Add To-Do</button>
        </form>
        {todos.map((todo) => (
          <div key

<details>
<summary>英文:</summary>

App.jsx

import './App.css'
import React, {useState} from 'react';
import { Link, Routes, Route } from 'react-router-dom';
import Calendar from "./components/calendar/calendar.jsx";
import ToDo from "./components/todolist/todolist.jsx";
import { useParams } from 'react-router-dom';

const App = () => {

return (
&lt;div&gt;
&lt;Routes&gt;
&lt;Route path=&#39;/&#39; element={&lt;Calendar  /&gt;} /&gt;
&lt;Route path=&#39;/todo/:id&#39; element={&lt;ToDo /&gt;} /&gt;
&lt;/Routes&gt;
&lt;/div&gt;
)

}

export default App;


calendar.jsx

import './calendar.css'
import {Link} from 'react-router-dom'
import React from "react";

const Calendar = () => {

return (
&lt;div className=&quot;month&quot;&gt;
&lt;h1&gt; February 2023 &lt;/h1&gt;
&lt;div className=&quot;names&quot;&gt;
&lt;div className=&quot;weekNames&quot;&gt;Monday&lt;/div&gt;
&lt;div className=&quot;weekNames&quot;&gt;Tuesday&lt;/div&gt;
&lt;div className=&quot;weekNames&quot;&gt;Wednesday&lt;/div&gt;
&lt;div className=&quot;weekNames&quot;&gt;Thursday&lt;/div&gt;
&lt;div className=&quot;weekNames&quot;&gt;Friday&lt;/div&gt;
&lt;div className=&quot;weekNames&quot;&gt;Saturday&lt;/div&gt;
&lt;div className=&quot;weekNames&quot;&gt;Sunday&lt;/div&gt;
&lt;/div&gt;
&lt;div className=&quot;week&quot;&gt;
&lt;div className=&quot;day&quot;&gt;1 &lt;Link to=&#39;/todo/1&#39;&gt; To-Do:  &lt;/Link&gt; &lt;/div&gt;
&lt;div className=&quot;day&quot;&gt;2 &lt;Link to=&#39;/todo/2&#39;&gt; To-Do:  &lt;/Link&gt; &lt;/div&gt;
&lt;div className=&quot;day&quot;&gt;3 &lt;Link to=&#39;/todo/3&#39;&gt; To-Do: &lt;/Link&gt; &lt;/div&gt;
&lt;div className=&quot;day&quot;&gt;4 &lt;Link to=&#39;/todo/4&#39;&gt; To-Do: &lt;/Link&gt; &lt;/div&gt;
&lt;div className=&quot;day&quot;&gt;5 &lt;Link to=&#39;/todo/5&#39;&gt; To-Do: &lt;/Link&gt; &lt;/div&gt;
&lt;div className=&quot;day&quot;&gt;6 &lt;Link to=&#39;/todo/6&#39;&gt; To-Do: &lt;/Link&gt; &lt;/div&gt;
&lt;div className=&quot;day&quot;&gt;7 &lt;Link to=&#39;/todo/7&#39;&gt; To-Do: &lt;/Link&gt; &lt;/div&gt;
&lt;div className=&quot;day&quot;&gt;8 &lt;Link to=&#39;/todo/8&#39;&gt; To-Do: &lt;/Link&gt;&lt;/div&gt;
&lt;div className=&quot;day&quot;&gt;9 &lt;Link to=&#39;/todo/9&#39;&gt; To-Do: &lt;/Link&gt; &lt;/div&gt;
&lt;div className=&quot;day&quot;&gt;10 &lt;Link to=&#39;/todo/10&#39;&gt; To-Do: &lt;/Link&gt; &lt;/div&gt;
&lt;div className=&quot;day&quot;&gt;11 &lt;Link to=&#39;/todo/11&#39;&gt; To-Do: &lt;/Link&gt; &lt;/div&gt;
&lt;div className=&quot;day&quot;&gt;12 &lt;Link to=&#39;/todo/12&#39;&gt; To-Do: &lt;/Link&gt; &lt;/div&gt;
&lt;div className=&quot;day&quot;&gt;13 &lt;Link to=&#39;/todo/13&#39;&gt; To-Do: &lt;/Link&gt; &lt;/div&gt;
&lt;div className=&quot;day&quot;&gt;14 &lt;Link to=&#39;/todo/14&#39;&gt; To-Do: &lt;/Link&gt; &lt;/div&gt;
&lt;div className=&quot;day&quot;&gt;15 &lt;Link to=&#39;/todo/15&#39;&gt; To-Do: &lt;/Link&gt; &lt;/div&gt;
&lt;div className=&quot;day&quot;&gt;16 &lt;Link to=&#39;/todo/16&#39;&gt; To-Do: &lt;/Link&gt; &lt;/div&gt;
&lt;div className=&quot;day&quot;&gt;17 &lt;Link to=&#39;/todo/17&#39;&gt; To-Do: &lt;/Link&gt; &lt;/div&gt;
&lt;div className=&quot;day&quot;&gt;18 &lt;Link to=&#39;/todo/18&#39;&gt; To-Do: &lt;/Link&gt; &lt;/div&gt;
&lt;div className=&quot;day&quot;&gt;19 &lt;Link to=&#39;/todo/19&#39;&gt; To-Do: &lt;/Link&gt; &lt;/div&gt;
&lt;div className=&quot;day&quot;&gt;20 &lt;Link to=&#39;/todo/20&#39;&gt; To-Do: &lt;/Link&gt; &lt;/div&gt;
&lt;div className=&quot;day&quot;&gt;21 &lt;Link to=&#39;/todo/21&#39;&gt; To-Do: &lt;/Link&gt; &lt;/div&gt;
&lt;div className=&quot;day&quot;&gt;22 &lt;Link to=&#39;/todo/22&#39;&gt; To-Do: &lt;/Link&gt; &lt;/div&gt;
&lt;div className=&quot;day&quot;&gt;23 &lt;Link to=&#39;/todo/23&#39;&gt; To-Do: &lt;/Link&gt; &lt;/div&gt;
&lt;div className=&quot;day&quot;&gt;24 &lt;Link to=&#39;/todo/24&#39;&gt; To-Do: &lt;/Link&gt; &lt;/div&gt;
&lt;div className=&quot;day&quot;&gt;25 &lt;Link to=&#39;/todo/25&#39;&gt; To-Do: &lt;/Link&gt; &lt;/div&gt;
&lt;div className=&quot;day&quot;&gt;26 &lt;Link to=&#39;/todo/26&#39;&gt; To-Do: &lt;/Link&gt; &lt;/div&gt;
&lt;div className=&quot;day&quot;&gt;27 &lt;Link to=&#39;/todo/27&#39;&gt; To-Do: &lt;/Link&gt; &lt;/div&gt;
&lt;div className=&quot;day&quot;&gt;28 &lt;Link to=&#39;/todo/28&#39;&gt; To-Do: &lt;/Link&gt; &lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
);

}

export default Calendar


todolist.jsx

import './todolist.css'
import React from "react";
import { NavLink } from "react-router-dom";
import { useParams } from 'react-router-dom';

const ToDo = () => {
const {id} = useParams()
const [todos, setTodos] = React.useState(() => JSON.parse(localStorage.getItem(todos-${id})) || []);
const [todo, setTodo] = React.useState("");
const [todoEditing, setTodoEditing] = React.useState(null);
const [editingText, setEditingText] = React.useState("");

React.useEffect(() => {
const json = JSON.stringify(todos);
localStorage.setItem(todos-${id}, json);
}, [todos, id]);

function handleSubmit(e) {
e.preventDefault();
const newTodo = {
id: new Date().getTime(),
text: todo,
completed: false,
};
setTodos([...todos].concat(newTodo));
setTodo("");
}

function deleteTodo(id) {
let updatedTodos = [...todos].filter((todo) => todo.id !== id);
setTodos(updatedTodos);
}

function toggleComplete(id) {
let updatedTodos = [...todos].map((todo) => {
if (todo.id === id) {
todo.completed = !todo.completed;
}
return todo;
});
setTodos(updatedTodos);
}

function submitEdits(id) {
const updatedTodos = [...todos].map((todo) => {
if (todo.id === id) {
todo.text = editingText;
}
return todo;
});
setTodos(updatedTodos);
setTodoEditing(null);
}

return (
<div>
<div align='right'>
<NavLink to='/' style={{textDecoration: 'none', color: 'black'}}><button className='btn'> Calendar View </button></NavLink>
</div>
<div id="todo-list">
<h1>To-Do For Today</h1>
<h2> Total Tasks: {todos.length} </h2>
<form onSubmit={handleSubmit}>
<input
type="text"
onChange={(e) => setTodo(e.target.value)}
value={todo}
/>
<button className="btn">Add To-Do</button>
</form>
{todos.map((todo) => (
<div key={todo.id} className="todo">
<div className="todo-text">
<input
type="checkbox"
id="completed"
checked={todo.completed}
onChange={() => toggleComplete(todo.id)}
/>
{todo.id === todoEditing ? (
<input
type="text"
onChange={(e) => setEditingText(e.target.value)}
/>
) : (
<div>{todo.text}</div>
)}
</div>
<div className="todo-actions">
{todo.id === todoEditing ? (
<button className='btnXS' onClick={() => submitEdits(todo.id)}>Submit</button>
) : (
<button className='btnXS' onClick={() => setTodoEditing(todo.id)}>Edit</button>
)}

          &lt;button className=&#39;btnXS&#39; onClick={() =&gt; deleteTodo(todo.id)}&gt;Delete&lt;/button&gt;
&lt;/div&gt;
&lt;/div&gt;
))}
&lt;/div&gt;
&lt;/div&gt;

);
};

export default ToDo;


I am trying to built a calendar web app with daily to-do lists. So when clicking on the link on any day, the user should be able to add and edit what to do for that day. But I would also like to show the total number of todos added for each day in the calendar page. E.g. &lt;div className=&quot;day&quot;&gt;1 &lt;Link to=&#39;/todo/1&#39;&gt; To-Do: &quot;show total numbers of to-dos for this day&quot;  &lt;/Link&gt; &lt;/div&gt;
I tried calling {todos.length} on the calendar page, but it always shows 0.
</details>
# 答案1
**得分**: 0
```jsx
我编辑了你的 Calendar.jsx 文件并添加了一个新的 Day 组件:
import './calendar.css'
import {Link} from 'react-router-dom'
import React from "react";
const Calendar = () => {
return (
<div className="month">
<h1> 2023年2月 </h1>
<div className="names">
<div className="weekNames">星期一</div>
<div className="weekNames">星期二</div>
<div className="weekNames">星期三</div>
<div className="weekNames">星期四</div>
<div className="weekNames">星期五</div>
<div className="weekNames">星期六</div>
<div className="weekNames">星期天</div>
</div>
<div className="week">
<Day number={1} />
<Day number={2} />
<Day number={3} />
<Day number={4} />
<Day number={5} />
<Day number={6} />
<Day number={7} />
</div>
</div>
);
}
function Day({number}){
const [todos, setTodos] = React.useState(() => JSON.parse(localStorage.getItem(`todos-${id}`)) || []);
return (<div className="day">{number} <Link to={`/todo/${number}`}> 待办事项: {todos.length} </Link> </div>);
}
export default Calendar;

Is that what you meant?

英文:

I edit your Calendar.jsx and add new Day Component :

import &#39;./calendar.css&#39;
import {Link} from &#39;react-router-dom&#39;
import React from &quot;react&quot;;
const Calendar = () =&gt; {
return (
&lt;div className=&quot;month&quot;&gt;
&lt;h1&gt; February 2023 &lt;/h1&gt;
&lt;div className=&quot;names&quot;&gt;
&lt;div className=&quot;weekNames&quot;&gt;Monday&lt;/div&gt;
&lt;div className=&quot;weekNames&quot;&gt;Tuesday&lt;/div&gt;
&lt;div className=&quot;weekNames&quot;&gt;Wednesday&lt;/div&gt;
&lt;div className=&quot;weekNames&quot;&gt;Thursday&lt;/div&gt;
&lt;div className=&quot;weekNames&quot;&gt;Friday&lt;/div&gt;
&lt;div className=&quot;weekNames&quot;&gt;Saturday&lt;/div&gt;
&lt;div className=&quot;weekNames&quot;&gt;Sunday&lt;/div&gt;
&lt;/div&gt;
&lt;div className=&quot;week&quot;&gt;
&lt;Day number={1} /&gt;
&lt;Day number={2} /&gt;
&lt;Day number={3} /&gt;
&lt;Day number={4} /&gt;
&lt;Day number={5} /&gt;
&lt;Day number={6} /&gt;
&lt;Day number={7} /&gt;
&lt;/div&gt;
&lt;/div&gt;
);
}
function Day({number}){
const [todos, setTodos] = React.useState(() =&gt; JSON.parse(localStorage.getItem(`todos-${id}`)) || []);
return (&lt;div className=&quot;day&quot;&gt;{number} &lt;Link to={`/todo/${number}`}&gt; To-Do: {todos.length} &lt;/Link&gt; &lt;/div&gt;);
}
export default Calendar;

Is that what you meant?

huangapple
  • 本文由 发表于 2023年2月13日 22:50:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/75437470.html
匿名

发表评论

匿名网友

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

确定