如何在不更新的情况下为 React 中的兄弟组件设置状态

how to have set state for sibling component in React without updating

我在 1 个父组件中有 2 个同级组件。是这样的:

import React, { useState } from 'react';
import PlaceSearchInput from './PlaceSearchInput';
import { GoogleMap, withGoogleMap } from "react-google-maps";

export default function Search(props) {
    const [mapCenter, setMapCenter] = useState({lat:3, lng:2});

    function Map() {

        return (
            <div>
            <GoogleMap defaultZoom={10} center={mapCenter}/>
            </div>
        )
    }

    const WrappedMap = withGoogleMap(Map);

    if (!props.isGoogleMapApiReady)
        return (
            <div>Loading...</div>
        )

    return (
        <div style={{ margin: "100px" }}>
           <div style={{ height: "50vh", width: "50vh" }}>
                <WrappedMap
                    loadingElement={<div style={{ height: "100%" }} />}
                    containerElement={<div id="map" style={{ height: "100%" }} />}
                    mapElement={<div style={{ height: "100%" }} />}
                />
                <PlaceSearchInput setMapCenter={setMapCenter} />
            </div>
        </div>
    )
}

我想要 Input 设置坐标,Map 显示坐标。我知道一种方法是在父级中设置坐标状态,然后将 set 函数传递给 Input,将坐标传递给 Map。但是通过这种方式,只要输入组件更改状态,我就会发现它,尽管 Map 确实移动到新坐标,Map 被刷新,这是我想要避免的。有办法解决吗?

试试这个,我将 Map 和 WrappedMap 的创建移出了搜索组件。 我相信每次重新渲染组件时组件定义的变化可能会导致反应认为它是一个全新的组件并卸载旧组件并安装新组件而不是重新渲染。

import React, { useState } from 'react';
import PlaceSearchInput from './PlaceSearchInput';
import { GoogleMap, withGoogleMap } from 'react-google-maps';

function Map({ center }) {
  return (
    <div>
      <GoogleMap defaultZoom={10} center={center} />
    </div>
  );
}

const WrappedMap = withGoogleMap(Map);

export default function Search(props) {
  const [mapCenter, setMapCenter] = useState({ lat: 3, lng: 2 });

  if (!props.isGoogleMapApiReady) {
    return <div>Loading...</div>;
  }
  return (
    <div style={{ margin: '100px' }}>
      <div style={{ height: '50vh', width: '50vh' }}>
        <WrappedMap
          loadingElement={<div style={{ height: '100%' }} />}
          containerElement={<div id="map" style={{ height: '100%' }} />}
          mapElement={<div style={{ height: '100%' }} />}
          center={mapCenter}
        />
        <PlaceSearchInput setMapCenter={setMapCenter} />
      </div>
    </div>
  );
}