现在我正在使用 laravel 和 react.js 创建用于编辑待办应用程序任务的端点,我使用 postman 对该端点进行了测试,它返回成功响应 http://localhost:8000/api/tasks/4and ...
现在我正在使用 laravel 和 react.js 创建用于编辑待办事项应用程序任务的端点,我使用 postman 对该端点进行了测试,它返回成功响应 http://localhost:8000/api/tasks/4,主体是
{
"user_id": 1,
"title": "Updated Task4",
"description": "Updated description",
"status": "completed",
"due_date": "2024-08-01",
"category_id": 1
}
以下是回复
{
"data": {
"id": 4,
"user_id": 1,
"title": "Updated Task4",
"description": "Updated description",
"status": "completed",
"due_date": "2024-08-01",
"category_id": 1,
"created_at": "2024-07-23T21:12:40.000000Z",
"updated_at": "2024-07-25T00:00:22.000000Z"
}
}
by creating edit-task component in react and implement this code in it
import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import axios from 'axios';
import { Helmet } from 'react-helmet';
import Joi from 'joi';
export default function EditTask() {
const { id } = useParams();
const navigate = useNavigate();
const [task, setTask] = useState({
user_id: '', // Initially empty
title: '',
description: '',
status: 'pending',
due_date: '',
category_id: ''
});
const [categories, setCategories] = useState([]);
const [loading, setLoading] = useState(false);
const [errors, setErrors] = useState({});
useEffect(() => {
fetchCategories();
fetchTask();
}, []);
const fetchCategories = async () => {
try {
const response = await axios.get('http://localhost:8000/api/categories');
setCategories(response.data.data);
} catch (error) {
console.error('Error fetching categories:', error);
}
};
const fetchTask = async () => {
try {
const response = await axios.get(`http://localhost:8000/api/tasks/${id}`);
setTask(response.data.data);
} catch (error) {
console.error('Error fetching task:', error);
}
};
const schema = Joi.object({
user_id: Joi.number().required(),
title: Joi.string().min(3).max(255).required(),
description: Joi.string().min(5).max(255).allow(''),
status: Joi.string().valid('pending', 'completed').required(),
due_date: Joi.date().allow(''),
category_id: Joi.number().required()
});
const handleChange = (e) => {
const { name, value } = e.target;
setTask(prevTask => ({
...prevTask,
[name]: value
}));
};
const handleSubmit = async (e) => {
e.preventDefault();
console.log('Form submitted'); // Debug log
console.log('Task data before submission:', task); // Log task data
const { error } = schema.validate(task, { abortEarly: false });
if (error) {
const validationErrors = {};
error.details.forEach(detail => {
validationErrors[detail.path[0]] = detail.message;
});
setErrors(validationErrors);
return;
}
setErrors({});
setLoading(true);
try {
const response = await axios.put(`http://localhost:8000/api/tasks/${id}`, task, {
headers: {
'Content-Type': 'application/json',
},
});
console.log('Response from server:', response); // Debug log
console.log('Updated task data:', response.data); // Debug log
if (response.status === 200) {
navigate('/tasks');
} else {
setErrors({ form: 'Failed to update task. Please try again.' });
}
} catch (error) {
console.error('Error updating task:', error);
setErrors({ form: 'Failed to update task. Please check the form data.' });
} finally {
setLoading(false);
}
};
return (
<>
<Helmet>
<meta charSet="utf-8" />
<title>Edit Task</title>
</Helmet>
<div className="container mt-5">
<h1>Edit Task</h1>
<form onSubmit={handleSubmit}>
<div className="mb-3">
<label htmlFor="title" className="form-label">Title</label>
<input
type="text"
className="form-control"
id="title"
name="title"
value={task.title}
onChange={handleChange}
placeholder="Enter task title"
required
/>
{errors.title && <small className="text-danger">{errors.title}</small>}
</div>
<div className="mb-3">
<label htmlFor="description" className="form-label">Description</label>
<textarea
className="form-control"
id="description"
name="description"
value={task.description}
onChange={handleChange}
placeholder="Enter task description"
/>
{errors.description && <small className="text-danger">{errors.description}</small>}
</div>
<div className="mb-3">
<label htmlFor="status" className="form-label">Status</label>
<select
className="form-select"
id="status"
name="status"
value={task.status}
onChange={handleChange}
required
>
<option value="pending">Pending</option>
<option value="completed">Completed</option>
</select>
{errors.status && <small className="text-danger">{errors.status}</small>}
</div>
<div className="mb-3">
<label htmlFor="due_date" className="form-label">Due Date</label>
<input
type="date"
className="form-control"
id="due_date"
name="due_date"
value={task.due_date}
onChange={handleChange}
/>
{errors.due_date && <small className="text-danger">{errors.due_date}</small>}
</div>
<div className="mb-3">
<label htmlFor="category_id" className="form-label">Category</label>
<select
className="form-select"
id="category_id"
name="category_id"
value={task.category_id}
onChange={handleChange}
required
>
<option value="">Select a category</option>
{categories.map(cat => (
<option key={cat.id} value={cat.id}>{cat.name}</option>
))}
</select>
{errors.category_id && <small className="text-danger">{errors.category_id}</small>}
</div>
{errors.form && <div className="alert alert-danger">{errors.form}</div>}
<button type="submit" className="btn invadebtn" disabled={loading}>
{loading ? <span className="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> : 'Update Task'}
</button>
</form>
</div>
</>
);
}
它不起作用它在控制台中记录更新的数据,但它既没有在数据库中更新,也没有将我导航到任务页面
更新数据库并导航至任务页面