語境
我正在嘗試用來google-map-react展示當地的面包店。
但是,console.log(props);我的子組件中的行StoresGoogleMap列印storeLocations為. 如果我在我的組件中使用 below ,則它正在作業:stores[]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>
);
};
uj5u.com熱心網友回復:
因為您在子組件的 useEffect 中傳遞了空陣列[],所以它在渲染時只運行第一次。
現在假設您的資料已被提取,因此子組件將被重新渲染,但您的 useEffect 將不會再次運行,因為您在依賴項中傳遞了一個空陣列。
因此,您可以安全地使用props.storeLocations.map或從中洗掉[],useEffect但這將導致useEffect在每個渲染上運行,因此您可以添加props.storeLocations到您的子useEffect依賴項。但是如果您僅將其用于渲染目的,我真的沒有看到使用與道具相同的子狀態的意義
uj5u.com熱心網友回復:
所以我認為這里的問題是子組件StoresGoogleMap在父組件SearchStoresPage中以初始值呈現,即[]。但是當父組件的狀態改變時不會更新。任何建議如何解決這個問題?
解決此問題的一種方法是useEffect在父組件中的資料更改時在子組件中觸發 --> 通過在useEffect()中添加props.storeLocations作為依賴 項StoresGoogleMap
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/432256.html
上一篇:向Google地圖添加新的點擊偵聽器時出錯。地圖是由PHP創建的JS創建的
下一篇:如何更新標記的資訊視窗?
