简体   繁体   English

在组件之间传递值 ReactJS

[英]Pass values between components ReactJS

I'm trying to pass id value from one component to another and that works.我正在尝试将 id 值从一个组件传递到另一个组件并且有效。 But when I want to get values based on this id it returns undefined.但是当我想根据这个 id 获取值时,它会返回 undefined。 I want to get access to value trains.number.我想访问 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.我在访问值 trains.number 时遇到问题,但是对于不值的值,一切看起来都很好。

this.state.station.trains it's an array, so you need to change it to: this.state.station.trains是一个数组,所以你需要把它改成:

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

And change changeCityHandles function to:并将changeCityHandles function 更改为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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