首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从formik datePicker向api发送dateFormat

如何从formik datePicker向api发送dateFormat
EN

Stack Overflow用户
提问于 2019-12-30 04:36:33
回答 1查看 1K关注 0票数 1

我想将我的日期格式作为dd-MM-yyyy发送到api,我可以让它在客户端显示正确的格式,但当我将它发送到api时,我会收到类似yyyy-MM-ddThh:mm:ss之类的内容,但我只想要日期。

这就是我所拥有的:

代码语言:javascript
复制
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格式。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-12-30 06:30:49

最简单的方法是修改onSubmit函数:

代码语言:javascript
复制
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函数中执行此操作是一个很好的方法。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59523058

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档