顶级函数-TypeError:Object(...)不是函数撰写

时间:2018-07-02 00:27:52

标签: reactjs react-google-maps recompose

在我的项目中,我正在使用recompose / react-google-maps定义顶级组件,如下所示:

const LocationPicker = compose(
    withProps({
        googleMapURL: "https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,places&key=AIzaSyDnKwHUG_EJXN5EEW6hTftZHYo8E8QTTXY",
        loadingElement: <div style={{ height: `100%` }} />,
        containerElement: <div style={{ height: `400px` }} />,
        mapElement: <div style={{ height: `100%` }} />,
    }),
    withScriptjs,
    withGoogleMap,
    withState('places', '', ''),
    withHandlers(() => {
        refs = {
            map: undefined,
        }

        return {
            onMapMounted: () => ref => {
                refs.map = ref
                service = new google.maps.places.PlacesService(refs.map.context.__SECRET_MAP_DO_NOT_USE_OR_YOU_WILL_BE_FIRED);
            },
        }
    }),
)((props) => {
    return (
        <GoogleMap
            ref={props.onMapMounted}
            defaultZoom={13}
            defaultCenter={{ lat: 42.3570637, lng: -71.06257679999999 }}
        >
            {props.marker &&
                <Marker position={{ lat: props.marker.lat, lng: props.marker.lng }} draggable={true} />
            }
        </GoogleMap>
    )
})

这是在类范围之外定义的Component。我收到以下错误: TypeError: Object(...) is not a function enter image description here 为什么不能这样定义组件?

1 个答案:

答案 0 :(得分:1)

首先,我将其分解为无状态功能组件,然后使用Recompose增强该组件。

const LocationPickerView = props => (
  <GoogleMap
    ref={props.onMapMounted}
    defaultZoom={13}
    defaultCenter={{ lat: 42.3570637, lng: -71.06257679999999 }}
  >
    {props.marker && (
      <Marker position={{ lat: props.marker.lat, lng: props.marker.lng }} draggable />
    )}
  </GoogleMap>
);

const LocationPicker = compose(
  withProps({
    googleMapURL:
      'https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,places&key=AIzaSyDnKwHUG_EJXN5EEW6hTftZHYo8E8QTTXY',
    loadingElement: <div style={{ height: '100%' }} />,
    containerElement: <div style={{ height: '400px' }} />,
    mapElement: <div style={{ height: '100%' }} />
  }),
  withScriptjs,
  withGoogleMap,
  withState('places', '', ''),
  withHandlers(() => {
    refs = {
      map: undefined
    };

    return {
      onMapMounted: () => ref => {
        refs.map = ref;
        service = new google.maps.places.PlacesService(
          refs.map.context.__SECRET_MAP_DO_NOT_USE_OR_YOU_WILL_BE_FIRED
        );
      }
    };
  })
)(LocationPickerView);

我认为这可以解决您的TypeError。 如果不是,请尝试注释掉refwithHandler部分。您可能在那里有单独的问题。