我有简单的表格归档,日期来自正确的日期格式的服务器 但日期字段中的日期不显示日期 我只能查看“描述”,而不是看起来像这样的日期:
import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import { useAuth } from "./security/AuthContext";
import {retriveTodoByIdAndName} from "../api/restApi";
import { Formik,Field,Form } from "formik";
function TodoComponent() {
const {id} = useParams()
const authContext = useAuth();
const userName = authContext.username
const [description,setDescription] = useState('')
const [targetDate,setTargeDate] = useState('')
useEffect(
() => retriveTodos(),[id]
)
function retriveTodos() {
console.log(`id:${id} userName:${userName}`)
retriveTodoByIdAndName(userName,id)
.then(
response => {
console.log(response)
setDescription(response.data.description)
setTargeDate(response.date.targetDate)
}
)
.catch(
response => {
console.log(
response => {
console.log(response)
}
)
}
)
}
return (
<div className="continer">
<h1>Enter Todo Details</h1>
<div>
<Formik initialValues={{description,targetDate}} enableReinitialize={true}>
{
(props) => (
<Form>
<fieldset className="form-group">
<label>Description</label>
<Field type="text" className="form-control" name="description" />
</fieldset>
<fieldset className="form-group">
<label>Target Date</label>
<Field type="date" className="form-control" name="targetDate" />
</fieldset>
</Form>
)
}
</Formik>
</div>
</div>
)
}
export default TodoComponent;
这是我从服务器得到的响应:
{
"data": {
"id": 1,
"username": "meiry",
"description": "Get AWS Certified",
"targetDate": "2033-03-09",
"done": false
},
"status": 200,
"statusText": "",
"headers": {
"content-type": "application/json"
},
"config": {
"transitional": {
"silentJSONParsing": true,
"forcedJSONParsing": true,
"clarifyTimeoutError": false
},
"adapter": [
"xhr",
"http"
],
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"maxBodyLength": -1,
"env": {},
"headers": {
"Accept": "application/json, text/plain, */*"
},
"baseURL": "http://localhost:8080",
"method": "get",
"url": "/users/xxxx/todos/1"
},
"request": {}
}
setTargeDate
函数好像有错别字。而不是response.date.targetDate
,它应该是response.data.targetDate
.
尝试将
retriveTodos
函数更新为:
function retriveTodos() {
console.log(`id:${id} userName:${userName}`)
retriveTodoByIdAndName(userName,id)
.then(
response => {
console.log(response)
setDescription(response.data.description)
setTargeDate(response.data.targetDate)
}
)
.catch(
response => {
console.log(
response => {
console.log(response)
}
)
}
)
}
这应该为 targetDate 状态设置正确的值并将其显示在表单字段中。