我创建了一个reactjs表单,可以将数据成功发送到django rest api。我想在单击按钮后重设表单,但它一直给我一个错误,说“ this.props.resetState()不是函数。是否可以做一些事情来重设之后创建的表单的所有输入提交?
import React, { Component } from "react";
import { Button, Form, FormGroup, Input, Label } from "reactstrap";
import axios from "axios";
import { API_URL } from "../constants";
class ClientForm extends React.Component {
constructor(props) {
super(props);
this.state = {
pk: 0,
name: "",
email: "",
business_name: "",
country: "",
};
}
componentDidMount() {
if (this.props.client) {
const {
pk,
name,
email,
phone,
business_name,
country,
} = this.props.client;
this.setState(pk, name, document, email, phone);
}
}
onChange = (e) => {
this.setState({ [e.target.name]: e.target.value });
};
createClient = (e) => {
e.preventDefault();
axios.post(API_URL, this.state).then(() => {
this.props.reset();
this.props.toggle();
});
};
editClient = (e) => {
e.preventDefault();
axios.put(API_URL + this.state.pk, this.state).then(() => {
this.props.reset();
this.props.toggle();
});
};
defaultIfEmpty = (value) => {
return value === " " ? " " : value;
};
render() {
return (
<Form onSubmit={this.props.client ? this.editClient : this.createClient}>
<FormGroup>
<Label for="name">Name:</Label>
<Input
type="text"
name="name"
onChange={this.onChange}
value={this.defaultIfEmpty(this.state.name)}
/>
</FormGroup>
<FormGroup>
<Label for="email">Email:</Label>
<Input
type="email"
name="email"
onChange={this.onChange}
value={this.defaultIfEmpty(this.state.email)}
/>
</FormGroup>
<FormGroup>
<Label for="phone">Phone Number:</Label>
<Input
type="text"
name="phone"
onChange={this.onChange}
value={this.defaultIfEmpty(this.state.phone)}
/>
</FormGroup>
<FormGroup>
<Label for="business_name">Business Name:</Label>
<Input
type="text"
name="business_name"
onChange={this.onChange}
value={this.defaultIfEmpty(this.state.business_name)}
/>
</FormGroup>
<FormGroup>
<Label for="country">Country:</Label>
<Input
type="text"
name="country"
onChange={this.onChange}
value={this.defaultIfEmpty(this.state.country)}
/>
</FormGroup>
<Button>Send</Button>
</Form>
);
}
}
export default ClientForm;
答案 0 :(得分:1)
由于在方法中使用的是controlled components,因此可以将组件状态重置为initialState
的值,然后在表单提交处理程序的末尾调用this.setState(this.initialState)
。
类似的东西:
class ClientForm extends React.Component {
constructor(props) {
super(props);
this.initialState = {
pk: 0,
name: "",
email: "",
business_name: "",
country: "",
};
this.state = this.initialState;
}
(...)
handleSubmit = (e) => {
e.preventDefault();
this.props.client ? this.editClient() : this.createClient();
this.setState(this.initialState);
}
(...)
render() {
return (
<Form onSubmit={this.handleSubmit}>
(...)
</Form>
);
}
}
export default ClientForm;
不要忘记删除e
和e.preventDefault()
方法中的createClient()
参数和editClient()
调用。