简体   繁体   中英

Pass values between components ReactJS

I'm trying to pass id value from one component to another and that works. But when I want to get values based on this id it returns undefined. I want to get access to value trains.number.

Here is code for component which I send values from:


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

        this.state = {
            stations: []
        }

        this.addStation = this.addStation.bind(this);
        this.editStation = this.editStation.bind(this);
        this.deleteStation = this.deleteStation.bind(this);
        this.showTrains = this.showTrains.bind(this);
    }

    deleteStation(id) {
        StationService.deleteStation(id).then(res => {
            this.setState({ stations: this.state.stations.filter(station => station.id !== id) });
        })
    }

    editStation(id) {
        this.props.history.push(`/add-station/${id}`);
    }

    componentDidMount() {
        StationService.getStations().then((res) => {
            this.setState({ stations: res.data });
        })
    }



    render() {
        return (
            <div>
                <div className="row">
                    <table className="table table-striped table-bordered">
                        <thead>
                            <tr>
                                <th>Miasto</th>
                                <th>Nazwa stacji</th>
                                <th>Pociągi</th>
                                <th>Akcja</th>
                            </tr>
                        </thead>

                        <tbody>
                            {this.state.stations.map(
                                station =>
                                    <tr key={station.id}>
                                        <td>{station.city}</td>
                                        <td>{station.name}</td>
                                        <td>{station.trains.map(item => item.number)}</td>
                                        {/* {console.log(station.trains.id)} */}
                                        {console.log(station.name)}
                                        <td>
                                            <button onClick={() => this.editStation(station.id)} className="btn btn-info">Modyfikuj</button>
                                            {console.log(this.state.stations)}
                                        </td>
                                    </tr>

                            )}

                        </tbody>
                    </table>
                </div>
            </div>
        );
    }
}

And the component which I'm trying to get values from looks like this:


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 })
            });
        }
        console.log(this.state.station.name + 'dfddddd');
    }

    changeCityHandles = (event) => {
        this.setState({ city: 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 }

        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="city" className="form-control" value={this.state.trains.number} onChange={this.changeCityHandles} />
                                    </div>
                                    
                                    {console.log(this.state.trains)}
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div >
        );
    }
}

I'm having trouble accessing to value trains.number, but with the values that are not in value everything looks fine.

this.state.station.trains it's an array, so you need to change it to:

<input  name="city" className="form-control" value={this.state.station.trains[0].number} onChange={this.changeCityHandles} />

And change changeCityHandles function to:

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

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