无法在ReactJS中使用useParams提取id

问题描述 投票:0回答:1

在我的应用程序中,我正在尝试编辑一个任务,这需要完成任务 id,但由于某种原因,我的 id 没有使用 useParams 提取。下面是我的 EditTask.jsx 代码,地址栏只显示 http://localhost:5173/todos/edit/:id

import React, { useState, useEffect } from "react";
import BackButton from "../components/BackButton.jsx";
import Spinner from "../components/Spinner.jsx";
import axios from "axios";
import { useNavigate, useParams} from "react-router-dom";

const EditTask = () => {
  const [task, setTask] = useState("");
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();
  const {id} = useParams();
  console.log(id);
  useEffect(() => {
    setLoading(true);
    axios
      .get(`http://localhost:5000/api/todos/${id}`)
      .then((res) => {
        setTask(res.data.task);
        setLoading(false);
      })
      .catch((error) => {
        setLoading(false);
        console.log(error);
      });
  }, []);
  const handleEditTask = () => {
    const data = {
      task,
    };
    setLoading(true);
    axios
      .put(`http://localhost:5000/api/todos/${id}`, data)
      .then(() => {
        setLoading(false);
        navigate("/");
      })
      .catch((error) => {
        setLoading(false);
        console.log(error);
      });
  };
  return (
    <div className="p-4">
      <BackButton />
      <h1 className="text-3xl my-4">{id}</h1>
      {loading ? <Spinner /> : ""}
      <div className="flex flex-col border-2 border-solid border-sky-400 rounded-xl w-[600px] p-4 mx-auto">
        <div className="my-4">
          <label className="text-xl mr-4 text-gray-500">Task</label>
          <input
            type="text"
            value={task}
            onChange={(e) => setTask(e.target.value)}
            className="border-2 border-solid border-gray-500 px-4 py-2 w-full"
          />
        </div>
        <button className="p-2 bg-sky-400" onClick={handleEditTask}>
          Edit
        </button>
      </div>
    </div>
    
  );
};

export default EditTask;

这是带有路由的 App.jsx

import React from 'react'
import { Routes, Route } from "react-router-dom";
import Home from "./pages/Home.jsx";
import CreateTask from "./pages/CreateTask.jsx";
import DeleteTask from "./pages/DeleteTask.jsx";
import EditTask from "./pages/EditTask.jsx";
import ShowTask from "./pages/ShowTask.jsx";

const App = () => {
  return (
    
    <Routes>
      <Route path="/" element={<Home/>}/>
      <Route path="/todos/create" element={<CreateTask/>}/>
      <Route path="/todos/details/:id" element={<ShowTask/>}/>
      <Route path="/todos/edit/:id" element={<EditTask/>}/>
      <Route path="/todos/delete/:id" element={<DeleteTask/>}/>
    </Routes>
  )
}

export default App

这是服务器端routes.js

router.put("/todos/:id", async (req, res) => {
  try {
    if (!req.body.task) {
      res.status(400).json({ msg: "empty task field" });
    }
    const { id } = req.params;
    const result = await taskModel.findByIdAndUpdate(id, req.body);
    if (!result) {
      return res.status(400).json({ msg: "task not found" });
    }
    return res.status(200).json({ msg: "task successfully updated" });
  } catch (error) {
    console.log(error);
  }
});

编辑请求使用 Postman 可以正常工作,并且当我硬编码“id”值而不是动态渲染它时也可以正常工作,当我控制台日志 id 时,它只显示 (:id)。应用程序应填充编辑任务字段,当单击编辑时,编辑和更新任务并返回 Home.jsx

在此输入图片描述

reactjs react-hooks react-router-dom mern
1个回答
0
投票

单击特定任务时,您可以使用这样的动态值

onClick={() => navigate(`/todos/edit/${todo.id}`)
© www.soinside.com 2019 - 2024. All rights reserved.