Реакция ввода формы отображает данные, которые нельзя изменить - PullRequest
0 голосов
/ 20 марта 2019

Я пытался добавить проверку в мою форму редактирования данных, но после попытки реализовать, я столкнулся с проблемой. В поле ввода вы можете увидеть, как выглядят текущие данные example ==> model = "Crawler", но если я хочу отредактировать эти данные, скажем, "Walker", и я хочу стереть crawler и набрать walker, он не будет работать это остается Crawler, вы не можете стереть его. Что странно, потому что до того, как я изменил свой код для реализации проверки, он работал нормально.

Мой код («Код в комментарии - это функции, которые я использовал до проверки»)

import * as React from 'react';
import { Link } from 'react-router-dom';
import { getDetail, update } from '../../services/vehicles.service';


export class VehicleEdit extends React.Component {
constructor(props) {
    super(props);

    const vehicleId = props.match.params.name;

    this.state = {
        vehicle: {},
        errors: {}
    };
    this.handleChange = this.handleChange.bind(this);
    this.onSubmit = this.onSubmit.bind(this);

    getDetail(vehicleId).then((response) => {
        this.setState({
            vehicle: response.message,
        });
    });
}
/* updateManufacturer(manufacturer) {
    this.setState({
        vehicle: {
            ...this.state.vehicle,
            manufacturer,
        },
    });
}

updateModel(model) {
    this.setState({
        vehicle: {
            ...this.state.vehicle,
            model,
        },
    });
}

updateCostInCredits(cost_in_credits) {
    this.setState({
        vehicle: {
            ...this.state.vehicle,
            cost_in_credits,
        },
    });
}

updateLength(length) {
    this.setState({
        vehicle: {
            ...this.state.vehicle,
            length,
        },
    });
}

updateMaxAtmosperingSpeed(max_atmosphering_speed) {
    this.setState({
        vehicle: {
            ...this.state.vehicle,
            max_atmosphering_speed,
        },
    });
}
updateCrew(crew) {
    this.setState({
        vehicle: {
            ...this.state.vehicle,
            crew,
        },
    });
}
updatePassengers(passengers) {
    this.setState({
        vehicle: {
            ...this.state.vehicle,
            passengers,
        },
    });
}
updateVehicleClass(vehicle_class) {
    this.setState({
        vehicle: {
            ...this.state.vehicle,
            vehicle_class,
        },
    });
}*/
handleChange(e) {
    let vehicle = this.state.vehicle;
    vehicle[e.target.name] = e.target.value;
    this.setState({
        vehicle
    });
}

onSubmit = (e) => {
    e.preventDefault();
    if (this.validateForm()) {
        let vehicle = {};
        vehicle["model"] = "";
        vehicle["manufacturer"] = "";
        vehicle["cost_in_credits"] = "";
        vehicle["max_atmosphering_speed"] = "";
        vehicle["crew"] = "";
        vehicle["passengers"] = "";
        vehicle["vehicle_class"] = "";
        this.setState({ vehicle: vehicle });

        update(this.state.vehicle.name, this.state.vehicle).then((response) => {
            this.props.history.push('/vehicles');
        });
        alert("Form submitted");
    }
}
validateForm() {

    let vehicle = this.state.vehicle;
    let errors = {};
    let formIsValid = true;

    if (!vehicle["model"]) {
        formIsValid = false;
        errors["model"] = "*Please enter a model type.";
    }
    if (!vehicle["manufacterer"]) {
        formIsValid = false;
        errors["emailid"] = "*Please enter a manufacterer.";
    }
    if (!vehicle["cost_in_credits"]) {
        formIsValid = false;
        errors["cost_in_credits"] = "*Please enter cost in credits.";
    }
    if (!vehicle["length"]) {
        formIsValid = false;
        errors["length"] = "*Please enter a length.";
    }
    if (!vehicle["max_atmosphering_speed"]) {
        formIsValid = false;
        errors["max_atmosphering_speed"] = "*Please enter max atmosphering speed.";
    }
    if (!vehicle["crew"]) {
        formIsValid = false;
        errors["crew"] = "*Please enter crew count.";
    }
    if (!vehicle["passengers"]) {
        formIsValid = false;
        errors["passengers"] = "*Please enter passengers count.";
    }
    if (!vehicle["vehicle_class"]) {
        formIsValid = false;
        errors["vehicle_class"] = "*Please enter vehicle class.";
    }

    this.setState({
        errors: errors
    });
    return formIsValid;


}


render() {
    return (

        <div className="margin-left">
            {(this.state.vehicle.name) ? (
                <form onSubmit={this.onSubmit}>
                    <h1>{this.state.vehicle.name}</h1>
                    <div>
                        <label >Model: </label><br />
                        <input type="text" name="model" id="model" value={this.state.vehicle.model} onChange={(e) => this.handleChange(e.target.value)} />
                        <div className="errorMsg">{this.state.errors.model}</div>

                    </div>
                    <div>
                        <label >Manufacturer: </label><br />
                        <input type="text" name="manufacturer" id="manufacturer" value={this.state.vehicle.manufacturer} onChange={this.handleChange} />
                        <div className="errorMsg">{this.state.errors.manufacturer}</div>

                    </div>
                    <div>
                        <label >Cost in credits: </label><br />
                        <input type="text" name="cost_in_credits" id="cost_in_credits" value={this.state.vehicle.cost_in_credits} onChange={this.handleChange} />
                        <div className="errorMsg">{this.state.errors.cost_in_credits}</div>

                    </div>
                    <div>
                        <label >Length: </label><br />
                        <input type="text" name="length" id="length" value={this.state.vehicle.length} onChange={this.handleChange} />
                        <div className="errorMsg">{this.state.errors.length}</div>

                    </div>
                    <div>
                        <label >Max atmosphering speed: </label><br />
                        <input type="text" name="max_atmosphering_speed" id="max_atmosphering_speed" value={this.state.vehicle.max_atmosphering_speed} onChange={this.handleChange} />
                        <div className="errorMsg">{this.state.errors.max_atmosphering_speed}</div>
                    </div>
                    <div>
                        <label >Crew: </label><br />
                        <input type="text" name="crew" id="crew" value={this.state.vehicle.crew} onChange={this.handleChange} />
                        <div className="errorMsg">{this.state.errors.crew}</div>
                    </div>
                    <div>
                        <label >Passengers: </label><br />
                        <input type="text" name="passengers" id="passengers" value={this.state.vehicle.passengers} onChange={this.handleChange} />
                        <div className="errorMsg">{this.state.errors.passengers}</div>
                    </div>
                    <div>
                        <label >Vehicle class: </label><br />
                        <input type="text" name="vehicle_class" id="vehicle_class" value={this.state.vehicle.vehicle_class} onChange={this.handleChange} />
                        <div className="errorMsg">{this.state.errors.vehicle_class}</div>
                    </div>
                    <br />
                    <button className="btn btn-outline-success" >Save changes</button>
                    <Link className="btn btn-danger" to={`/vehicles/${this.state.vehicle.name}`}>Back </Link>
                </form>
            ) : (<p>Loading student details...</p>)}
        </div>

    );
  }
}
export default VehicleEdit;

Может кто-нибудь увидеть, где я ошибся? Потому что я этого не вижу

----------- Обновление в скрипте vehicle.service отсюда данные отправляются на мой API

 export const update = (name, vehicle, vehicles) => fetch(`${url}/vehicles/${name}/edit`, { 
    method: 'PUT', 
    body: JSON.stringify(vehicle),
    mode: 'cors', 
    headers: new Headers({
        'Content-Type': 'application/json',
    })
}).then((response) => {
    if(response.statusText === 'OK') {
        return response.json();
    }
    throw new Error('Something went wrong UPDATING vehicle with name' + name);
});

-----> Функция обновления в моем API

app.put('/vehicles/:name/edit', (req, res) => {
 let vehicle = null;
       console.log('update vehicle', [req.body]);

    if (vehicles[0] && vehicles[0].length) {
        vehicle = vehicles[0].filter((vehicle) => ('' + vehicle.name) === req.params.name);
    }

    if (vehicle) {
        vehicles = vehicles[0].map((s) => {
            return ('' + s.name) === req.params.name ? vehicles.push[req.body] : s;
        })

        res.send({
            status: config.STATUS.OK,
            message: [req.body],
        });
    } else {
        res.send({
            status: config.STATUS.ERROR,
            message: 'Could not find vehicle for update',
        });
    }
});

1 Ответ

0 голосов
/ 20 марта 2019

Ваша функция handleChange требует e, но ваша модель передает ее e.target.value.

...