我一直在尝试使用React,Spring和Fetch API更新我在我的应用程序中拥有的实体,它看起来可以保存状态,但没有任何改变。
安装组件时,我会加载注释(我的应用程序中的实体)的信息,并且可以使用输入来更改它们。使用console.log我已经看到React的状态已经更新,但是我认为我没有在Spring中正确保存。这是我的代码:
反应
import React, { Component } from 'react';
import { Button } from 'reactstrap';
class EditAnnotation extends Component {
constructor(props) {
super(props);
this.state = {
name: '',
text: '',
date: '',
isLoading: false
}
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
const name = event.target.name;
this.setState({ [name]: event.target.value });
}
componentDidMount() {
this.setState({isLoading: true});
fetch("http://localhost:8080/annotations/" + this.props.id)
.then(response => response.json())
.then(data => this.setState({name: data.name, text: data.text, date: data.date.substring(0,10), isLoading: false}));
}
handleSubmit(event) {
event.preventDefault();
fetch('http://localhost:8080/annotations/' + this.props.id, {
method: 'PUT',
headers: {'Content-Type':'application/json'},
body: JSON.stringify({
name: this.state.name,
text: this.state.text,
date: this.state.date
})
}).then(response => response.json())
.then(data => this.setState({name: data.name, text: data.text, date: data.date.substring(0,10)}))
console.log(this.state.name, this.state.text, this.state.date);
}
render() {
const { name, text, date } = this.state;
return(
<div>
<div>Editar anotación</div>
<div>
<form onSubmit={ this.handleSubmit }>
<label>
Título:
<input type="text" value={ name } name="name" onChange={ this.handleChange } />
</label>
<label>
Texto:
<input type="text" value={ text } name="text" onChange={ this.handleChange }/>
</label>
<label>
Fecha:
<input type="date" value={ date } name="date" onChange={ this.handleChange }/>
</label>
<Button type="submit" color="danger" >Confirmar</Button>
</form>
</div>
</div>
)
}
}
export default EditAnnotation;
春天
@PutMapping("/annotations/{id}")
@CrossOrigin(origins = "http://localhost:3000")
public ResponseEntity<Annotation> updateOrReplaceAnnotation(@Valid @RequestBody Annotation newAnnotation, @PathVariable Long id) {
log.info("Request to update annotation: {}", newAnnotation);
Optional<Annotation> annotations = repository.findById(id);
if(null != newAnnotation.getName()) {
annotations.get().setName(newAnnotation.getName());
}
if(null != newAnnotation.getText()) {
annotations.get().setText(newAnnotation.getText());
}
if(null != newAnnotation.getDate()) {
annotations.get().setDate(newAnnotation.getDate());
}
return annotations.map(response -> ResponseEntity.ok().body(response))
.orElseThrow(() -> new AnnotationNotFoundException(id));
}
handleSubmit()中的Console.log显示在输入中修改的正确值,但是按下后不会在数据库中更新。
先谢谢大家。