我正在学习React,我有这个虚拟项目,后端与Spring Boot,每次我发送POST请求它击中数据库并生成自动ID,但其余字段是空的。我已经将表单属性从"值"更改为"defaultValue",因为"值"是不可编辑的。我知道有几个线程有类似的问题,但没有一个是帮助我。
export function withRouter(Children) {
return (props) => {
const match = { params: useParams() };
return <Children {...props} match={match} />
}
}
class CategoryEdit extends Component {
emptyItem = {
catName: '',
catDescription: ''
};
constructor(props) {
super(props);
this.url = "http://localhost:8080/categories";
this.state = {
item: this.emptyItem
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
async componentDidMount() {
if (this.props.match.params.id !== 'add') {
const category = await (await fetch(`${this.url}/${this.props.match.params.id}`)).json();
this.setState({ item: category });
}
}
handleChange(event) {
const target = event.target;
const value = target.value;
const name = target.name;
let item = { ...this.state.item };
item[name] = value;
this.setState({ item });
}
async handleSubmit(event) {
event.preventDefault();
const { item } = this.state;
await fetch('http://localhost:8080/categories/add' + (item.id ? '/' + item.id : ''), {
method: (item.id) ? 'PUT' : 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true
},
body: JSON.stringify(item),
});
};
render() {
const { item } = this.state;
const title = <h2>{item.id ? 'Edit Category' : 'Add Category'}</h2>;
console.log(item);
return <div>
<Container>
<AppNavBar />
{title}
<Form onSubmit={this.handleSubmit}>
<FormGroup>
<Label for="catName"> Category Name</Label>
<Input type="text" name="catName" id="catName" defaultValue ={item.catName || ''}
onChange={this.handleChange} autoComplete="catName" />
</FormGroup>
<FormGroup>
<Label for="catDescription">Description</Label>
<Input type="text" name="catDescription" id="catDescription" defaultValue ={item.catDescription || ''}
onChange={this.handleChange} autoComplete="catDescription" />
</FormGroup>
<FormGroup>
<Button color="primary" type="submit">Save</Button>{' '}
<Button color="secondary" tag={Link} to="/">Cancel</Button>
</FormGroup>
</Form>
</Container>
</div>
}
}
export default withRouter(CategoryEdit);
结束点
控制器
@CrossOrigin(origins = "http://localhost:3000")
@RestController
@RequestMapping("/categories")
public class CategoryRestController {
@Autowired
CategoryService cs;
@PostMapping("/add")
public Category saveCat(Category cat) {
return cs.addNewCategory(cat);
}
}
实体import lombok.Data;
@Data
@Entity
@Table(name = "category")
public class Category implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private Integer catId;
private String catName;
private String catDescription;
}
服务@Service
public class CategoryService {
@Autowired
private CategoryRepository cr;
public Category addNewCategory(Category category) {
return cr.save(category);
}
}
库
public interface CategoryRepository extends JpaRepository<Category, Integer> {
}
将您的代码(稍作修改以适应TS)添加到这个沙箱中,它工作得很好。属性实际上应该是value
,而不是defaultValue
,因为它会将组件从非受控更改为受控。此外,Access-Control-Allow-*
标头在这里没有价值,它们是从服务器发送的响应标头,而不是请求标头。至于空值,您可能需要检查api端点处理程序是否更改了这些值或期望使用其他格式。