Как передать значения для редактирования страницы? - PullRequest
0 голосов
/ 04 мая 2020

Попытка передать значения на страницу редактирования формы. Я просматривал несколько учебных пособий и следовал определенному методу, но не смог этого сделать. Возможность удалить элементы из таблицы, но застрял с функцией редактирования. Я новичок в React и все еще учусь на go, поэтому любая помощь будет оценена.

Это моя страница управления местоположением:

import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';

const Location = props => (
  <tr>
    <td>{props.location.name}</td>
    <td>{props.location.address}</td>
    <td>{props.location.vehicleCapacity}</td>
    <td>
      <Link to={"/edit/" + props.location.name}>edit</Link> | <a href="#" onClick={() => { props.deleteLocation(props.location.name) }}>delete</a>
    </td>
  </tr>
)

export default class ManageLocation extends Component {
  constructor(props) {
    super(props);

    this.deleteLocation = this.deleteLocation.bind(this)

    this.state = {location: []};
  }

  componentDidMount() {
    axios.get('http://localhost:8080/locations/')
      .then(response => {
        this.setState({ location: response.data })
      })
      .catch((error) => {
        console.log(error);
      })
  }

  deleteLocation(id) {
    axios.delete('http://localhost:8080/location/?name='+id)
      .then(response => { console.log(response.data)});

    this.setState({
      location: this.state.location.filter(el => el.name !== id)
    })
  }

  locationList() {
    return this.state.location.map(item => {
      return <Location location={item} deleteLocation={this.deleteLocation} key={item.name}/>;
    })
  }

  render() {
    return (
      <div>
        <h3>Manage Locations</h3>
        <table className="table">
          <thead className="thead-light">
            <tr>
              <th>Name</th>
              <th>Address</th>
              <th>Vehicle Capacity</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            { this.locationList() }
          </tbody>
        </table>
      </div>
    )
  }
}

Это мой editLocation.jsx

import React, { Component } from 'react';
import axios from 'axios';

export default class EditLocation extends Component {
  constructor(props) {
    super(props);

    this.onChangeName = this.onChangeName.bind(this);
    this.onChangeAddress = this.onChangeAddress.bind(this);
    this.onChangevehicleCapacity = this.onChangevehicleCapacity.bind(this);

    this.state = {
      name: '',
      address: '',
      vehicleCapacity: 0,
    }
  }

  componentDidMount() {
    axios.get('http://localhost:8080/location' + this.props.match.params.id)
      .then(response => {
        this.setState({
          name: response.data.name,
          address: response.data.address,
          vehicleCapacity: response.data.vehicleCapacity,
        })
      })
      .catch(function (error) {
        console.log(error);
      })
  }

  onChangeName(e) {
    this.setState({
      name: e.target.value
    })
  }

  onChangeAddress(e) {
    this.setState({
      address: e.target.value
    })
  }

  onChangevehicleCapacity(e) {
    this.setState({
      vehicleCapacity: e.target.value
    })
  }

  onSubmit(e) {
    e.preventDefault();

    const location = {
      name: this.state.name,
      address: this.state.address,
      vehicleCapacity: this.state.vehicleCapacity,
    }

    console.log(location);

    axios.post('http://localhost:8080/location' + this.props.match.params.id, location)
      .then(res => console.log(res.data));

    window.location = '/';
  }

  render() {
    return (
    <div>
      <h3>Edit Location</h3>
      <form onSubmit={this.onSubmit}>
        <div className="form-group"> 
          <label>Name: </label>
          <input type="text"
              required
              className="form-control"
              value={this.state.name}
              onChange={this.onChangeName}/>
        </div>
        <div className="form-group"> 
          <label>Address: </label>
          <input  type="text"
              required
              className="form-control"
              value={this.state.address}
              onChange={this.onChangeAddress}
              />
        </div>
        <div className="form-group">
          <label>Vehicle Capacity: </label>
          <input 
              type="text" 
              className="form-control"
              value={this.state.vehicleCapacity}
              onChange={this.onChangevehicleCapacity}
              />
        </div>

        <div className="form-group">
          <input type="submit" value="Edit Location" className="btn btn-primary" />
        </div>
      </form>
    </div>
    )
  }
}

Это маршрутизатор. js, где мой товарищ по команде написал конечные точки для редактирования местоположения

 router.put('/location', passport.authenticate('jwt', {session: false}), User.checkIsInRole(User.Roles.Admin),
  (req,res) => {
    locationDetails.findOne({ name: req.query.name}).then((loc)=> {
      if (loc){
        //check number of vehicles cuurently
        vehicleDetails.find({location: loc.name}).then((vehicles) => {
          if (vehicles.length <= req.body.vehicleCapacity) {
            loc.address = req.body.address;
            loc.vehicleCapacity = req.body.vehicleCapacity;
            loc.save();
            return res.send(loc);
          } else {
            return res.status(400).send("This location already has more vehicles than "+ req.body.vehicleCapacity);
          }
        })
      } else {
        return res.status(400).send("This location name already exists "+obj);
      }
    })
  })
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...