React重组如何异步更新状态

时间:2019-02-28 11:36:08

标签: reactjs recompose

我开始使用recompose并与StateHandlers函数一起使用,但是当道具中有新数据并且无法理解该方法时,我需要更新状态。

import React from "react";
import {compose, withProps, withStateHandlers} from "recompose"
import {GoogleMap, InfoWindow, Marker, withGoogleMap, withScriptjs} from "react-google-maps"
import './Map.module.css'

const mapGoogle = compose(
    withProps({
        googleMapURL:
            "https://maps.googleapis.com/maps/api/js&v=3.exp&libraries=geometry,drawing,places",
        loadingElement: <div style={{height: `100%`}}/>,
        containerElement: <div style={{height: "100vh", width: "100%"}}/>,
        mapElement: <div style={{height: "100%"}}/>,
    }),

这里我想从获取的道具中更新状态=>

withStateHandlers(
    props => ({
        infoWindows: props.markers ? props.markers.map(p => {
            return {isOpen: false};
        }) : null
    }),
    {
        onToggleOpen: ({infoWindows}) => selectedIndex => ({
            infoWindows: infoWindows ? infoWindows.map((iw, i) => {
                iw.isOpen = selectedIndex === i;
                return iw;
            }) : null
        })
    }
),

如果props.markers不为空,我想将它们放在地图上

    withScriptjs,
    withGoogleMap
)(props => {
    let markers = null;
    if (props.markers) {
        console.log(props.markers);
        markers = props.markers.map((place, i) => {
            let lat = parseFloat(place.latitude);
            let lng = parseFloat(place.longitude);

            return (
                <Marker
                    id={place.id}
                    key={place.id}
                    position={{lat: lat, lng: lng}}
                    title="Click to zoom"
                    onClick={props.onToggleOpen.bind(this, i)}
                >
                    {props.infoWindows[i].isOpen && (
                        <InfoWindow onCloseClick={props.onToggleOpen.bind(i)}>
                            <div>{place.description}</div>
                        </InfoWindow>
                    )}
                </Marker>
            );
        })
    }
    return (
        <GoogleMap defaultZoom={props.zoom} defaultCenter={props.center}>
            {markers}
        </GoogleMap>
    )
});

export default mapGoogle;

0 个答案:

没有答案