我有一个用于表单的选择选项子组件(称为Service
),因为我正在用JSON文件加载值。另外,我在event.preventDefault()
事件中使用handleSubmit()
,以便成功显示react-notifications
成功消息,而不是由于重新渲染而立即消失。
这导致我的选择选项字段保持提交表单之前选择的值。我需要将它们重置为键0,以便获得“新鲜”表单。
我意识到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
成功消息仍会显示。但是此刻似乎只有一种可能。
答案 0 :(得分:0)
您需要将函数参数传递给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))