#reactjs #rest #post #material-ui
#reactjs #остальное #Публикация #material-ui
Вопрос:
У меня есть POST API, для которого требуется тело запроса в этой форме :
{
"module_id": 7,
"module_type": "Post-Reading",
"module_name": "Course Overview",
"duration": 70,
}
Теперь ниже приведен мой код реакции, я не могу продолжить, как в том, как отправить тело запроса.
Кроме того, я хочу последовательно обновлять module_id.
Может кто-нибудь, пожалуйста, помочь с этим. Я знаю, что есть много ошибок, пожалуйста, помогите в исправлении.
import React, { useState, useEffect } from 'react'
import Icon from '@material-ui/core/Icon';
import { makeStyles } from '@material-ui/core/styles';
import { TextField } from '@material-ui/core';
import InputLabel from '@material-ui/core/InputLabel';
import FormHelperText from '@material-ui/core/FormHelperText';
import FormControl from '@material-ui/core/FormControl';
import Select from '@material-ui/core/Select';
import NativeSelect from '@material-ui/core/NativeSelect';
import MenuItem from '@material-ui/core/MenuItem';
import Timeline from '@material-ui/lab/Timeline';
import TimelineItem from '@material-ui/lab/TimelineItem';
import TimelineSeparator from '@material-ui/lab/TimelineSeparator';
import TimelineConnector from '@material-ui/lab/TimelineConnector';
import TimelineContent from '@material-ui/lab/TimelineContent';
import TimelineOppositeContent from '@material-ui/lab/TimelineOppositeContent';
import TimelineDot from '@material-ui/lab/TimelineDot';
import FastfoodIcon from '@material-ui/icons/Fastfood';
import LaptopMacIcon from '@material-ui/icons/LaptopMac';
import HotelIcon from '@material-ui/icons/Hotel';
import RepeatIcon from '@material-ui/icons/Repeat';
import Paper from '@material-ui/core/Paper';
import Typography from '@material-ui/core/Typography';
import axios from 'axios';
const useStyles = makeStyles((theme) => ({
formControl: {
margin: theme.spacing(1),
minWidth: 120,
},
selectEmpty: {
marginTop: theme.spacing(2),
},
}));
const NewModule = () => {
const classes = useStyles();
const [state, setState] = useState({});
const [moduleid, setModuleId] = useState(0);
const [moduletype, setModuleType] = useState("");
const [modulename, setModuleName] = useState("");
const [duration, setDuration] = useState(0);
const [dropdown, setDropdown] = useState([]);
useEffect(() => {
axios.get("http://localhost:8083/getmoduletypes")
.then(res => {
setDropdown(res.data)
})
.catch(error => {
console.log(error)
});
}, []);
const handleDropdownChange = (event) => {
const name = event.target.name;
setDropdown({
...dropdown,
[name]: event.target.value,
});
};
const handleChangeModuleType = (event) => {
const name = event.target.name;
setModuleType({
...moduletype,
[name]: event.target.value,
});
};
const handleChangeDuration = (event) => {
const name = event.target.name;
setDuration({
...duration,
[name]: event.target.value,
});
};
state = {moduleid, moduletype, modulename, duration};
const submitHandler = (e) => {
e.preventDefault();
axios.post("http://localhost:8083/createmodule", state)
.then( response => {
console.log(response)
})
.catch( error => {
console.log(error)
})
console.log(moduletype);
}
return (
<div class="container">
<div class="row" style={{ width: "350px", marginTop: "20px", marginLeft: "30px", height: "450px" }}>
<div>
<Icon color="primary"><b> Add New Module</b></Icon>
</div>
<FormControl variant="outlined" onSubmit={submitHandler }>
<InputLabel id="demo-simple-select-outlined-label" >Choose Module Type</InputLabel>
<Select
labelId="demo-simple-select-outlined-label"
id="demo-simple-select-outlined"
onChange={() => handleDropdownChange}
label="TypeList"
>
{
dropdown.map(options =>
<MenuItem value={options["module_type"]} >{options["module_type"]}</MenuItem>
)}
</Select>
<TextField
style={{ marginTop: "10px" }}
id="outlined-helperText"
label="Module Name"
onChange={handleChangeModuleType}
variant="outlined"
/>
<TextField
style={{ marginTop: "20px" }}
id="outlined-helperText"
label="Course Duration"
onChange={handleChangeDuration}
variant="outlined"
/>
<div style={{ margin: "auto", marginTop: "20px" }}>
<button type="submit" class="btn btn-success" >ADD</button>
</div>
</FormControl>
</div>
</div>
)
}
export default NewModule;
Пожалуйста, дайте мне знать, как отправлять данные в том же формате, также корректны ли обработчики onChangeHandlers для всего.
Спасибо!
Комментарии:
1. Помог ли мой ответ направить вас на правильный путь?
Ответ №1:
Вы хотите инкапсулировать свои компоненты в элемент формы, например, так, а затем определить функцию handleSubmit (или как бы вы ее ни называли)
Затем в вашем handleSubmit вы можете использовать выборку для отправки данных формы в свой API в любом формате, который вы хотите. Обычно я беру свои данные и использую JSON.stringify(), чтобы превратить их в строку JSON, аналогичную вашим требованиям.
return (
<div class="container">
<form onSubmit={handleSubmit}>
<div class="row" style={{ width: "350px", marginTop: "20px", marginLeft: "30px", height: "450px" }}>
<div>
<Icon color="primary"><b> Add New Module</b></Icon>
</div>
<FormControl variant="outlined" onSubmit={submitHandler }>
<InputLabel id="demo-simple-select-outlined-label" >Choose Module Type</InputLabel>
<Select
labelId="demo-simple-select-outlined-label"
id="demo-simple-select-outlined"
onChange={() => handleDropdownChange}
label="TypeList"
>
{
dropdown.map(options =>
<MenuItem value={options["module_type"]} >{options["module_type"]}</MenuItem>
)}
</Select>
<TextField
style={{ marginTop: "10px" }}
id="outlined-helperText"
label="Module Name"
onChange={handleChangeModuleType}
variant="outlined"
/>
<TextField
style={{ marginTop: "20px" }}
id="outlined-helperText"
label="Course Duration"
onChange={handleChangeDuration}
variant="outlined"
/>
<div style={{ margin: "auto", marginTop: "20px" }}>
<button type="submit" class="btn btn-success" >ADD</button>
</div>
</FormControl>
</div>
</form>
</div>
)
}