我正试图使用axios post方法将一个新用户添加到我的数据库中,使用我用material ui制作的表单,应用程序运行良好。它不会标记我任何控制台错误或在浏览器中,如果它向我显示表单,但我无法编写TextFields。
在添加函数之前,我可以写得很好,但在添加Onchange和value之后,我不再让自己写
可能会发生什么?
组件
import React, { useState } from "react";
import axios from 'axios';
//useState hook create a state named user with initial state set to an object with name, lastname and age properties set to empty strings
function UserAdd(props) {
const initialState = { name: '', lastname: '', age:0 }
const [user, setUser] = useState(initialState)
function handleChange(event) {
setUser({...user, [event.target.name]: event.target.value})
}
function handleSubmit(event) {
event.preventDefault();
if(!user.name || !user.lastname || !user.age) return
async function postUser() {
try {
const response = await post('/api/addUser', user);
props.history.push(`/user/${response.data._id}`);
} catch(error) {
console.log('error', error);
}
}
postUser();
}
function handleCancel() {
props.history.push("/users");
}
return (
<div style={{ padding: 16, margin: 'auto', maxWidth: 1000 }}>
<Typography variant="h4" align="center" component="h1" gutterBottom>
Add User
</Typography>
<form onSubmit={handleSubmit} className={classes.container} >
<TextField
label="Name"
className={classes.textField}
value={user.name}
onChange={handleChange}
margin="normal"
variant="outlined"
/>
<TextField
id="filled-read-only-input"
label="Lastname "
className={classes.textField}
value={user.lastname}
onChange={handleChange}
margin="normal"
variant="outlined"
/>
<TextField
required
id="filled-required"
label="Age"
className={classes.textField}
value={user.age}
onChange={handleChange}
margin="normal"
variant="outlined"
/>
<Grid item style={{ marginTop: 30 }}>
<Button
variant="contained"
color="primary"
type="submit">
Add
</Button>
</Grid>
<Grid item style={{ marginTop: 30 }}>
<Button
onClick={handleCancel}
variant="contained"
type="cancel">
Cancel
</Button>
</Grid>
</form>
</div>
);
}
export default UserAdd;```
看起来需要有一个name
属性才能与event.target.name
一起传递。不确定TextField
需要什么道具,但我想它应该是这样的:
<TextField
name="name" // Add this
label="Name"
className={classes.textField}
value={user.name}
onChange={handleChange}
margin="normal"
variant="outlined"
/>
类似地,您需要为其他输入组件提供一个name
道具。