简体   繁体   中英

Getting undefined values in ReactJs

I'm trying to get values and insert them in the dropdown. But when I try to do that I get value as undefined instead of proper value. I want to get values from train array and populate dropdown with them. When I get station.name correct value is returned, but when i try to access train.number undefined value is returned.

import React, { Component } from 'react';
import StationService from '../services/StationService';

class CreateStationComponent extends Component {
    constructor(props) {
        super(props)

        this.state = {
            station: {
                id: this.props.match.params.id,
                city: '',
                name: '',
                trains: [
                    {
                        number: '',
                        numberOfCarriages: ''
                    }
                ]
            }
        }

        this.changeCityHandles = this.changeCityHandles.bind(this);
        this.changeNameHandles = this.changeNameHandles.bind(this);
        this.saveStation = this.saveStation.bind(this);
    }

    componentDidMount() {

        if (this.state.station.id === '_add') {
            return;
        } else {
            StationService.getStationById(this.state.station.id).then((res) => {
                let station = res.data;
                this.setState({ name: station.name, city: station.city, number: station.trains.number })
            });
        }
        // console.log(this.state.station.name + 'dfddddd');
    }

    changeCityHandles = (event) => {
        this.setState({ number: this.state.station, trains: event.target.value });
    }

    changeNameHandles = (event) => {
        this.setState({ name: event.target.value });
    }

    saveStation = (e) => {
        e.preventDefault();
        let station = { city: this.state.city, name: this.state.name, number: this.state.train.number, numberOfCarriages: this.state.train.numberOfCarriages }

        if (this.state.station.id === '_add') {
            StationService.createStation(station).then(res => {
                this.props.history.push('/stations');
            });
        } else {
            StationService.updateStation(station, this.state.station.id).then(res => {
                this.props.history.push('/stations');
            });
        }
    }

    cancel() {
        this.props.history.push('/stations');
    }

    getTitle() {
        if (this.state.id === '_add') {
            return <h3 className="text-center">Dodaj stację</h3>
        } else {
            return <h3 className="text-center">Modyfikuj stację</h3>
        }
    }

    render() {
        return (
            <div>
                <div className="container">
                    <div className="row">
                        <div className="card-body">
                            <form>

                                <div className="form-group">
                                    <input  name="name" className="form-control" value={this.state.name} onChange={this.changeNameHandles} />
                                </div>

                                    <select>
                                        {this.state.station.trains.map(train => <option key={train.id} value={train.number}>{train.number}</option>)}

                                    </select>
  
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        );
    }
}
    Try this:-
    
        {this.state.station && this.state.station.trains.length && 
 && this.state.station.trains.map((train , i) => {
                return (
                     <React.Fragment>
                            { train && train?.number &&
          <option key={train?.id} value={train?.number}>{train?.number}</option>       
                             }
                     </React.Fragment>
                          );
         })
    }

It's trains[0].number not trains.number , because the object you are trying to access is nested in an array.

StationService.getStationById(this.state.station.id).then((res) => {
                let station = res.data;
                this.setState({ name: station.name, city: station.city, number: station.trains.number })
            });

This code tries to set state variables of name, city and number. Instead try doing this

            StationService.getStationById(this.state.station.id).then((res) => {
                let station = res.data;
                this.setState({ station: { 
                     ...state.station,
                     name: station.name,
                     city: station.city,
                     trains: station.trains }
                 })
               });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM