[英]React Forms and axios
I have a Django REST api that I am consuming the POST endpoint in React using Axios.我有一个 Django REST api 我正在使用 ZD3E28535C73CCEE281 在 React 中使用 POST 端点。
Here is my React code:这是我的反应代码:
class FormComponent extends React.Component{
constructor(props){
super(props);
this.state = {
shipment: {
requestType: ""
}
};
this.handleChange = this.handleChange.bind(this);
this.handleFormSubmission = this.handleFormSubmission.bind(this);
}
submitRequest = (event) =>{
axios.post("http://localhost:8000/app/shipments/create/", this.state.shipment)
.then((data) =>{
console.log(data);
}).catch((error) =>{
console.log(error);
});
}
handleChange(event){
//selecting shipment from the state
const request = this.state.shipment;
//updating the shipment keys and values
request[event.target.name]= event.target.value
//setting the state
this.setState({shipment: request});
console.log("Input change detected")
}
handleFormSubmission(event){
event.preventDefault();
console.log("Submitted Successfully!");
console.log(this.state.shipment);
}
render() {
return (
<form className="parent-container" onSubmit={this.handleFormSubmission}>
<select className="quoteOrLabel" name="quoteOrLabel" value={this.state.shipment.requestType} onChange={this.handleChange} placeholder="Request Type" required>
<option>Quote</option>
<option>Label</option>
</select>
</form>
);
} }
My Questions are:我的问题是:
* *
I want the value of requestType in the state in the constructor of the class to change whenever the user selects an option from the dropdown menu tag?每当用户从下拉菜单标签中选择一个选项时,我希望 class 的构造函数中 state 中的 requestType 值发生变化?
My other question is in Google Chrome console, when I click on submit button, I see that the data gets submitted, but it does not get passed into Django REST api POST endpoint using axios. My other question is in Google Chrome console, when I click on submit button, I see that the data gets submitted, but it does not get passed into Django REST api POST endpoint using axios. I want it to be passed to the backend.*
我希望它被传递到后端。*
import React from 'react';
class FormComponent extends React.Component{
constructor(props){
super(props);
this.state = {
shipment: { requestType: ""},
options: [{id:1,name:"apple"},{id:2,name:"banana"},{id:3,name:"orange"}] // if you getting options data dynamiclly, fetch it in componentDidMount and use setState
};
}
change =(event)=>{
let shipment ={requestType:event?.target?.value}
this.setState({shipment});
}
submitRequest = () =>{
let {shipment,options} = this.state
let id = shipment.requestType || 1 // id is empty means its the first element which is apple
alert(id)
// send id to backend ...
}
render() {
let {options} = this.state
return (<><select onChange={this.change}>
{options.map((option) => (
<option value={option.id}> {option.name} </option>
))}
</select>
<button onClick={this.submitRequest}>submit</button>
</>);
}
}
export default FormComponent
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.