Проблемы с обновлением с Fetch в React - PullRequest
0 голосов
/ 13 января 2019

Я пытался обновить сущность, имеющуюся в моем приложении, с помощью 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));
    }

Console.log в handleSubmit () печатает правильное значение, измененное во входных данных, но после нажатия оно не обновляется в базе данных.

Заранее спасибо, ребята.

...