如何将数据从组件传递到另一个组件

时间:2019-09-05 19:39:16

标签: reactjs

我试图将某些数据(对API的获取响应)从一个组件传递到另一个组件,但是我找不到传递它们的方法。

在类AddresForm中,我从表单获取序列化的数据,该数据通过fecth方法发送到API。响应中包含重要信息,我需要在其他组件中使用响应中包含的信息。

class AddressForm extends React.Component{

constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.validatePredio = this.validatePredio.bind(this);

    this.state = {
        isApartment: false,
        required: false
    };

    this.cities = [];
    this.cities.push(["11001" ,"XXX"]);
    this.cities.push(["05001", "YYY"]);
    this.cities.push(["76001", "ZZZ"]);

}

handleSubmit(event) {
    event.preventDefault();
    const data = serialize(event.target, { hash: true });

    data['direccion'] = data['direccion']+"+"+data['num1']+"+"+data['num2']+"+"+data['num3'];

    fetch('https://api.....', {
        method: 'POST',
        headers: header,
        body: JSON.stringify(data),
    })
        .then((response) => response.json())
        .then((responseData) => {
            console.log(responseData);  // this data is needed in another component (MapSection)

        });
}

在该类中,我需要使用从上一组件获取的响应,确切地说,我需要使用一些坐标来绘制Map。

export class MapSection extends React.Component{

constructor(props) {
    super(props);
    this.setState = this.setState.bind(this);
}

state = {
    address: null
};

get googleMapDiv(){
    return document.getElementById("mapa");
}

googleMapRef = createRef();

render(){

    console.log(this.props,this.googleMapRef);

    return(
            <section className="hidden2" id="mapaSection">
                <div className="container">
                    <div className="row mt-5">
                        <div className="col mt-5">
                            <h3>Confirma la ubicación de tu inmueble</h3>

                            <div className="row mt-5">
                                <div className="col">
                                    <p id="direccionGeo"> {this.state.address !== null ? this.state.address : ""} </p>
                                </div>
                            </div>

                            <div id="mapa"
                                  ref={this.googleMapRef}
                                  style={{ width: 'auto', height: '55vh' }}
                                 className="card-panel white map-holder"
                                  />


                            <div className="botonesMapa row mt-5">
                                <div className="col-6" align="center">
                                    <button type="button" className="btn btn-info corregirBtn">Corregir dirección</button>
                                </div>
                                <div className="col-6" align="center">
                                    <button type="button" className="btn btn-info confirmarBtn">Ubicación correcta</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </section>
    )
}

componentDidMount() {

    const self = this;
    const googleMapScript = document.createElement('script');
    googleMapScript.src = 'https://maps.googleapis.com/maps/api/js?key=yourKEY';
    window.document.body.appendChild(googleMapScript);

    googleMapScript.addEventListener('load',() => {

        var coord = { lat: 4.6903289512, lng: -74.0522237222};

        this.googleMap =  this.createGoogleMap(coord);
        this.marker = this.createMarker();

        window.google.maps.event.addListener(this.marker, 'dragend', function(e) {

            var request = {
                "entrada": "address",
                "mpio_ccdgo": "11001",
                "lat": e.latLng.lat(),
                "lng": e.latLng.lng()
            };

            fetch('https://api....', {
                method: 'POST',
                headers: header,
                body: JSON.stringify(request),
            }).then((response) => response.json())
            .then(responseData => {
                self.setState({
                    address: responseData.direccion_formato
                });
            });

        });

    });

}

createGoogleMap = ( data ) => {
    return new window.google.maps.Map(this.googleMapRef.current, {
        zoom: 16,
        center:{
            lat: data.lat, //4.6903289512
            lng: data.lng//-74.0522237222
        },
        disableDefaultUI: true
    });
};
createMarker = () => {
    return new window.google.maps.Marker({
        position: {lat: 4.6903289512, lng: -74.0522237222},
        map: this.googleMap,
        title: 'Avaluamos',
        draggable: true
    });
};

}

最后我有了一个将所有组件都连接起来的类

class InitialForm extends React.Component{

constructor(props) {
    super(props);
}

render(){
    return(
        <div>
            <AddressForm />
            <MapSection/>
            <FeaturesForm/>
        </div>
    )
}

}

非常感谢您的时间和知识。

1 个答案:

答案 0 :(得分:0)

一个想法是向InitialForm添加一个方法,该方法采用字符串并将其保存为InitialForm的状态。您可以将此方法作为对AddressForm的支持,并以api响应作为参数进行调用。现在您在InitialForm中得到了响应,您可以将其传递给MapSection。 清楚吗?