我正在使用React,Formik和react-select. 我在国家/地区的下拉选择字段中遇到问题。
在我提交表单之前,我可以看到表单既有值又有标签:
console.log(this.props.values.billing_information_attributes.address_attributes.country )
返回这个{value: "United States", label: "United States"}
在我提交表单并且发布请求以失败响应(这是出于测试目的而期望的失败)后,所有其他表单都保留其值,但此下拉列表除外。现在console.log只返回相同的"United States"
要使下拉菜单起作用,需要以前面提到的格式提供一个对象,{value: "United States", label: "United States"}否则下拉菜单将显示为空白。显然,我可以使用 解决方法并再次设置字段值setFieldValue,但我觉得我在 Formik 生命周期方面遗漏了一些东西。另一件重要的事情是,在我发送发布请求之前,我正在修改我发送到服务器的数据,并且只发送国家的值,而不是整个值和标签对象,如下所示:
newParams["billing_information_attributes"]["address_attributes"]["country"] =
params["billing_information_attributes"]["address_attributes"]["country"].value
这是我的发帖请求:
handleSubmit = (params, actions) => {
Stripe.card.createToken(
{
number: params.card_number,
cvc: params.security_id,
exp_month: params.exp_month,
exp_year: params.exp_year,
address_zip: params.billing_information_attributes.address_attributes.postal_code
},
(status, response) => {
params.stripe_card_token = response.id
axios
.request("/order/complete", {
method: "patch",
data: {
order: modifiedParams(params, "checkoutForm"),
authenticity_token: this.props.authenticity_token,
agree_to_terms: params.agree_to_terms,
save_new_card: params.save_new_card,
saved_cards: params.saved_cards.value
}
})
.then(({ data }) => {
if (data.success) {
actions.resetForm()
actions.setStatus({ message: data.message })
window.location.replace("/order/" + data.order_id)
} else {
actions.setErrors({ server: data.errors })
actions.setStatus({ message: data.message})
console.log(data)
}
actions.setSubmitting(false)
document.querySelector(".flashMsg").scrollIntoView({ behavior: "smooth" })
})
.catch(error => {
console.log(error)
actions.setSubmitting(false)
actions.setErrors({ server: ["Cannot submit form at the moment. Please try again."] })
document.querySelector("body").scrollIntoView({ behavior: "smooth" })
})
}
)
}
任何人都可以帮助弄清楚为什么在提交和发布请求之后this.props.values.billing_information_attributes.address_attributes.country更改的值会以失败响应?谢谢!{value: "United States", label: "United States"}United States