为什么我的子组件没有从父组件获得状态更新



上下文

我想用google-map-react来展示当地的面包店。

但是,我的子组件StoresGoogleMap中的行console.log(props);storeLocationsstores打印为[]。如果我在StoresGoogleMap组件中使用以下内容,则它正在工作:

{props.storeLocations.map((storeLocation) => (
<Marker
key={storeLocation.unique_store_name}
lat={storeLocation.store_location_latitude}
lng={storeLocation.store_location_longitude}
store={storeLocation}
/>
))}

所以我认为这里的问题是,子组件StoresGoogleMap是用父组件SearchStoresPage中的初始值来呈现的,即[]。但在父组件的状态发生更改时不会更新。

有什么建议吗?

详细信息

我有一个定义如下的父组件:

const SearchStoresPage = () => {
const [state, setState] = React.useState<StateProperties>(
{stores:[], storeLocations: []} 
);
React.useEffect(
() => {
searchStores()
.then(
response => {
const locations : GoogleMapStoreLocation[] = response.map( 
(obj:TypeStore) => {
return (
{
store_id: obj['store_id'],
store_name: obj['store_name'],
unique_store_name: obj['unique_store_name'],
store_description: obj['store_description'],
store_website: obj['store_website'],
store_cell_number: obj['store_cell_number'],
store_email: obj['store_email'],
store_location: obj['store_location'],
store_location_latitude: obj['store_location_latitude'],
store_location_longitude: obj['store_location_longitude'],
show: false
} 
)
}
);
setState({stores: response, storeLocations: locations});
}
)
.catch(error => console.log(error));  
}, 
[]
);
return (
<div className="flex flex-row">
<StoreList storeList = {state.stores}/>
<StoresGoogleMap storeLocations = {state.storeLocations} stores = {state.stores} defaultCenter={[40.7831, -73.9712]}/>    
</div>
);
};

我有一个子组件StoresGoogleMap,定义如下:

const StoresGoogleMap = (props: StoresGoogleMapProps) => {
const [storeLocations, setStoreLocations] = React.useState<GoogleMapStoreLocation[]>(props.storeLocations);
React.useEffect(
() => {
console.log(props);
setStoreLocations(props.storeLocations);
}, 
[]
);
const onMarkerClick = (unique_store_name: string) => {
...
};
return (
<div id="map" style={{ height: '100vh', width: '100%' }}>
<GoogleMap
defaultZoom={12}
defaultCenter={props.defaultCenter}
bootstrapURLKeys={{ key: process.env.REACT_APP_GOOGLE_MAP_API_KEY }}
onChildClick={onMarkerClick}
>
{storeLocations.map((storeLocation) => (
<Marker
key={storeLocation.unique_store_name}
lat={storeLocation.store_location_latitude}
lng={storeLocation.store_location_longitude}
store={storeLocation}
/>
))}
</GoogleMap>

</div>
);

};

因为您在子组件的useEffect中传递空数组[],所以它在渲染时只运行第一次。

现在假设您的数据已被提取,因此子组件将被重新渲染,但您的useEffect将不会再次运行,因为您在依赖项中传递了一个空数组。

因此,您可以安全地使用props.storeLocations.map或从useEffect中删除[],但这将导致useEffect在每个渲染上运行,因此您可以将props.storeLocations添加到子useEffect依赖项中。但是我真的不认为使用与道具相同的子状态有什么意义,如果你使用它只是为了渲染

所以我认为这里的问题是,子组件StoresGoogleMap是用父组件SearchStoresPage中的初始值呈现的,即[]。但在父组件的状态发生更改时不会更新。有什么建议吗?

解决此问题的方法是在父组件中的数据发生更改时激发子组件中的useEffect-->通过在StoresGoogleMap中添加props.storeLocations作为依赖项useEffect((

最新更新