react-google-maps StandaloneSearchBox卸载

时间:2018-04-24 17:14:39

标签: reactjs google-maps

我正在尝试使用https://www.npmjs.com/package/react-google-maps

中的StandaloneSearchBox组件

在查看docs和其他一些答案之后,我实现了这样的组件:

import React, { Component } from "react";
import PropTypes from "prop-types";
import { withScriptjs } from "react-google-maps";
import StandaloneSearchBox from "react-google-maps/lib/components/places/StandaloneSearchBox";
import { Input } from "semantic-ui-react";
import API_KEY from "../config/googleAPIkey";

class AddressSearchbox extends Component {
  constructor(props) {
    super(props);
    this.searchboxRef = null;
  }

  onSearchBoxMounted = ref => {
    this.searchboxRef = ref;
  };

  onPlacesChanged = () => {
    const places = this.searchboxRef.getPlaces();
    this.props.onPlaceSelect(places[0]);
  };

  render() {

    const Searchbox = withScriptjs(props => (
      <StandaloneSearchBox
        ref={props.onSearchBoxMounted}
        onPlacesChanged={props.onPlacesChanged}
      >
        <Input
          type="text"
          placeholder="Type address or google place name"
          icon="search"
        />
      </StandaloneSearchBox>
    ));

    return (
      <Searchbox
        googleMapURL={`https://maps.googleapis.com/maps/api/js?key=${API_KEY}&v=3.exp&libraries=geometry,drawing,places`}
        loadingElement={<div style={{ height: `100%` }} />}
        onPlacesChanged={this.onPlacesChanged}
        onSearchBoxMounted={this.onSearchBoxMounted}
      />
    );
  }
}

AddressSearchbox.propTypes = {
  onPlaceSelect: PropTypes.func.isRequired
};

export default AddressSearchbox;

我在注册表单中使用该组件,其中所有其他输入字段更新输入更改的状态,从而导致重新呈现整个表单。 当重新呈现AddressSearchbox组件时,它似乎被卸载然后重新安装导致闪烁。组件本身工作正常。

编辑:当记录onSearchBoxMounted()中传递的ref参数时,它会在每次重新渲染后打印null,然后输出SearchBox对象,因此根据this,SearchBox组件将被卸载

1 个答案:

答案 0 :(得分:0)

我不确定它是否仍然存在,但是要解决此问题,您需要在类定义之前从render函数中提取此部分:

const Searchbox = withScriptjs(props => (....))

所以它看起来像这样:

imports ...

const Searchbox = withScriptjs(props => (....))

class AddressSearchbox extends Component {
  ...
  render() {
    return (
      <Searchbox .../>
    );
  }
}
  

实际上,大多数React应用程序只调用一次ReactDOM.render()。
  来源:https://reactjs.org/docs/rendering-elements.html

您会看到这种闪烁,因为每次状态更改时ReactJS都会运行render()函数。