【问题标题】:Stop React Google AutoComplete <input> component re-rendering but render everything else on selection停止 React Google AutoComplete <input> 组件重新渲染,但在选择时渲染其他所有内容
【发布时间】:2020-03-31 11:56:27
【问题描述】:

在 React 中,当我从 AutoComplete 中选择任何内容时,它会重新渲染 Input 元素,我如何才能阻止它重新渲染仅 Input 元素但重新渲染其他所有内容?

到目前为止我已经尝试过:

  1. 要使用 shouldComponentUpdate() 但要么我使用不正确,要么其他东西不起作用:How to stop the google map from re rendering and keeping just the values in input fields when marker is placed on different locations?

  2. 并按照此处的建议将 AutoComplete 组件与 Class 组件分开放置:https://github.com/tomchentw/react-google-maps/issues/220

演示在这里运行:https://codesandbox.io/s/suspicious-ride-5ht4o

【问题讨论】:

  • 将 state 关键字更改为您的姓名或其他您在 state 中设置的数据不一定要在您的 state 中,最好不要在 state 中以获得更好的性能。我猜想如果您将自动完成组件与 AsyncMap 分开,您的问题将如何解决。
  • 你怎么知道通过分离它会修复它?

标签: reactjs react-component react-google-maps


【解决方案1】:

来自shouldComponentUpdate(nextProps, nextState) documentation

请注意,返回 false 不会阻止子组件 当状态改变时重新渲染。

这就是 AutoCompleteTest 子组件在您的示例中被重新渲染的原因。

您可以通过以这种方式组织 Map 组件来防止 GoogleMapAutocomplete 组件重新渲染:

function App() {
  const AsyncMap = withScriptjs(
    withGoogleMap(mapProps => {
      return (
        <div>
          <Map
            defaultZoom={15}
            defaultCenter={{ lat: 55.686757, lng: 21.157926 }}
          />
        </div>
      );
    })
  );

  return (
    <AsyncMap
      googleMapURL={MAPS_URL}
      loadingElement={<div style={{ height: `100%` }} />}
      containerElement={<div style={{ height: "200px" }} />}
      mapElement={<div style={{ height: `100%` }} />}
    />
  );
}

在哪里

class Map extends Component {
  constructor(props) {
    super(props);
    this.state = {
      currentPosition: props.defaultCenter
    };
    this.handlePlaceSelected = this.handlePlaceSelected.bind(this);
  }

  handlePlaceSelected(place, input) {
    this.setState({
      currentPosition: {
        lat: place.geometry.location.lat(),
        lng: place.geometry.location.lng()
      }
    });
  }

  render() {
    return (
      <div>
        <GoogleMap
          defaultZoom={this.props.defaultZoom}
          defaultCenter={this.state.currentPosition}
          center={this.state.currentPosition}
        >
          <Marker position={this.state.currentPosition} />
        </GoogleMap>
        <Autocomplete
          style={{
            width: "90%",
            height: "40px",
            marginTop: "10px"
          }}
          onPlaceSelected={this.handlePlaceSelected}
          types={[]}
        />
      </div>
    );
  }
}

注意:

  • center 需要与 defaultCenter 属性一起显式指定 GoogleMap 组件以更新地图中心

Here is a demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-17
    • 1970-01-01
    • 2021-06-07
    • 2021-06-26
    • 1970-01-01
    • 2021-06-19
    • 2018-04-22
    相关资源
    最近更新 更多