我想将我的日期格式作为dd-MM-yyyy发送到api,我可以让它在客户端显示正确的格式,但当我将它发送到api时,我会收到类似yyyy-MM-ddThh:mm:ss之类的内容,但我只想要日期。
这就是我所拥有的:
import DatePicker from "react-datepicker";
export class AdminPage extends React.Component {
constructor(props){
super(props);
this.state = {
initialValues: {
dato: new Date()
}
};
}
handleChange = date => {
this.setState({
dato: date
});
};
render(){
let {initialValues} = this.state;
return(
<div>
<h1 className="signupheader">Arbejds seddel</h1>
<div>
<Formik
initialValues={initialValues}
validationSchema={Yup.object().shape({
dato: Yup.string().min(3, 'der skal flere tal på').required('husk at udfylde dato')
})}
onSubmit={(values, { setStatus, setSubmitting }) => {
setStatus();
fetch('https://nameless-ocean-57332.herokuapp.com/arbejdsseddel', {
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(values)
})
.then((response) => (response.json()))
.catch(error => console.log(error));
}}
>
{({ values }) => {
return(
<Form>
<div className="form-group">
<label htmlFor="dato">
Dato<span className="req">*</span>
</label>
<DatePicker className='form-control'
selected={this.state.dato}
onChange={dato => this.handleChange(dato)}
value={Selection}
dateFormat="dd-MM-yyyy"
withPortal
disabledKeyboardNavigation
/>
</div>
<button type="submit" className="btn btn-primary" disabled={isSubmitting}>Send som E-mail</button>
{isSubmitting &&
<img alt="" src="data:image/gif" />
}
</div>
{status &&
<div className={'alert alert-danger'}>{status}</div>
}
<button type="submit" className="btn btn-primary">Print</button>
</div>
</Form>
)
}}
</Formik>
);
}
}所以我只想让api接收我的自定义格式,而不是iso格式。
发布于 2019-12-30 06:30:49
最简单的方法是修改onSubmit函数:
onSubmit={(values, { setStatus, setSubmitting }) => {
const yourDate = values.dato;
const yourFormattedDate =
yourDate.getDate() +
"-" +
(yourDate.getMonth() + 1) +
"-" +
yourDate.getFullYear();
const updatedValues = { ...values, dato: yourFormattedDate }
setStatus();
fetch("https://nameless-ocean-57332.herokuapp.com/arbejdsseddel", {
method: "post",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(updatedValues)
})
.then(response => response.json())
.catch(error => console.log(error));
}}在将其发送到API之前,您需要以所需的方式重新格式化它。当然,一种更优雅的方式是,当您的Datepicker组件将返回字符串,但您没有提供任何有关它的信息。
有时,在将表单数据发送到后端之前,很难避免手动重新格式化表单数据,例如,当API需要某种奇怪的格式时。在这里,在onSubmit函数中执行此操作是一个很好的方法。
https://stackoverflow.com/questions/59523058
复制相似问题