我有一个用于表单的选择选项子组件(称为 Service
),因为我正在使用 JSON 文件加载值。此外,我在我的 handleSubmit()
事件中使用了 event.preventDefault()
以便正确显示 react-notifications
成功消息,而不是由于重新渲染而立即消失。
这导致我的选择选项字段保持在提交表单之前选择的值。我需要将这些重置为 key 0,以便我有一个"new"表单。
我意识到 event.preventDefault()
会阻止表单自然重置,因此我会在之后清除表单元素的状态。不过,这不会重置选择选项。
我尝试删除 event.preventDefault()
并且这允许表单重置,但是我的 react-notification
成功消息没有显示。
我曾尝试将 react-notification
消息放入不同的生命周期方法 (componentDidUpdate()
),但我没有成功,因为成功消息没有显示。
处理提交
handleSubmit(event) {
event.preventDefault();
let formData = {
name: this.state.name,
phone: this.state.phone,
email: this.state.email,
service1: this.state.service1,
service2: this.state.service2,
service3: this.state.service3
};
fetch('/emails/requestform', {
method: 'post',
body: JSON.stringify(formData),
headers: {
"Content-Type": "application/json"
}
}).then(
this.createNotification('success'),
this.setState({name: ''}),
this.setState({phone: ''}),
this.setState({email: ''}),
this.setState({service1: ''}),
this.setState({service2: ''}),
this.setState({service3: ''})
).catch(error => console.log(`Error posting form: ` + error));
}
服务组件
import React from 'react';
import './Service.css';
class Service extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.handleSubmitForSelect = this.handleSubmitForSelect.bind(this);
}
handleChange(event) {
this.props.onServicesChange(event.target.value);
}
handleSubmitForSelect(event) {
this.setState(event.target.value = '');
}
render() {
let services = this.props.state.services;
let optionItems = services.map((service) => <option key={service.id} value={service.value}>{service.service}</option>);
return (<div >
<select className="select" value={this.props.value} onChange={this.handleChange} onSubmit={this.handleSubmitForSelect}>
{optionItems}
</select>
</div>)
}
}
export default Service;
我希望表单完全重置并且 react-notification
成功消息仍然显示。但目前看来只有其中一种可能。
最佳答案
您需要将函数参数传递给 then()
。然后你的业务逻辑进入函数内部
fetch('/emails/requestform', {
method: 'post',
body: JSON.stringify(formData),
headers: {
"Content-Type": "application/json"
}
})
.then((resp) => resp.ok ? resp.json() : Promise.reject('Bad request status = '+ resp.status))
.then((data) => {
// ^^^^^^^^^^ anonymous function argument
// do something with response data here
this.createNotification('success');// <== semi colon not comma
this.setState({
name: '',
phone: '',
email: '',
service1: '',
service2: '',
service3: ''
});
}).catch((err)=> console.error(err))
关于javascript - 选择选项子组件不会在使用 React js 提交的表单上重置为键 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55506367/