我正在从API获取数据,想知道如何在输入字段中设置获取的日期。这似乎是一个绝对初学者的问题,无论如何,请帮助我。
下面是我的代码:export default function Consumerdetails() {
const [consumer, getConsumer] = useState([]);
useEffect(() => {
httpClient(url + `/api/consumers`).then((res) => {
console.log('Success:', res)
})
.catch(err => {
console.log('An error occurred:', err.res)
});
});
return (
<div>
<TextField
required
id="outlined-required"
label="User Name"
variant="outlined"
name="username"
value={consumer.username} onChange={getConsumer}
/>
<TextField
required
id="outlined-required"
label="Phone Number"
variant="outlined"
name="phone"
value={consumer.phone} onChange={getConsumer}
/>
</div>
})
您可以将api response分配给state,也可以将state分配给输入字段。
export default function Consumerdetails() {
const [consumer, getConsumer] = useState({});
useEffect(() => {
httpClient(url + `/api/consumers`)
.then(res => res.json()
.then((data) => {
getConsumer(data);
})
)
.catch(err => {
console.log('An error occurred:', err.res)
});
},[]);
return (
<div>
<TextField
required
id="outlined-required"
label="User Name"
variant="outlined"
name="username"
value={consumer?.username} onChange={getConsumer}
/>
<TextField
required
id="outlined-required"
label="Phone Number"
variant="outlined"
name="phone"
value={consumer?.phone} onChange={getConsumer}
/>
</div>
})
你可以这样设置API响应数据
export default function Consumerdetails() {
const [consumer, setConsumer] = useState([]);
// dummy json data
const data = {
username: "xyz",
mobile: "123456789",
};
useEffect(() => {
// your api data
setConsumer(data);
}, []);
const onChange = (event) => {
// here set change value
setConsumer(event.target.value);
};
return (
<div>
<TextField
required
id="outlined-required"
label="User Name"
variant="outlined"
name="username"
value={consumer.username}
onChange={onChange}
/>
<TextField
required
id="outlined-required"
label="Phone Number"
variant="outlined"
name="phone"
value={consumer.mobile}
onChange={onChange}
/>
</div>
);
}
useEffect(() => {
httpClient(url + `/api/consumers`).then((res) => {
getConsumer(res.data) // you store the data
})
.catch(err => {
console.log(err)
});
},[]);
检查它是否适合你