Я понял это с помощью комментария Альваро к моему основному посту.
Вот что я сделал. Сначала я переместил код, который генерирует LocationMarker s, в SearchLocationsScreen . В любом случае я уже обращался к местоположениям, необходимым для этих маркеров на этом экране (первоначально я передавал эти местоположения компоненту Map и создавал их там). В SearchLocationsScreen я перебираю все местоположения, чтобы сгенерировать LocationMarker s, добавляя обратный вызов, который использует хук useReducer для хранения состояния мода. Поскольку они оба находятся на одном уровне, я могу заполнить поля для модальной модели правильными данными из состояния редуктора. Этот обратный вызов передается LocationMarker s. Затем в LocationMarker onPress я вызываю этот метод. Все работает как положено. Вот обновленный код:
SearchLocationsScreen
const SearchLocationsScreen = ({isFocused, navigation}) => {
const {updateLocation} = useContext(CurrentLocationContext);
// hooks
const callback = useCallback((location) => {
updateLocation(location)
}, []);
const [err] = useCurrentLocation(isFocused, callback);
const [businessLocations] = useGetLocations();
const modalRef = useRef(null);
let locations = [];
if (businessLocations) {
for (let x = 0; x < businessLocations.length; x++) {
locations.push({
...businessLocations[x],
latitude: businessLocations[x].lat,
longitude: businessLocations[x].lng,
key: x,
})
}
}
const modalReducer = (state, action) => {
console.log("payload: ", action.payload);
switch (action.type) {
case 'show_modal':
return {...state,
companyName: action.payload.companyName,
companyAddress: action.payload.companyAddress,
waitTime: action.payload.waitTime
};
default:
return state;
}
};
const [modalState, dispatch] = useReducer(modalReducer, {
companyName: "Company Name",
companyAddress: "123 Elm St",
waitTime: 0
});
const createMarkers = () => {
let result = [];
if (locations) {
for (let i = 0; i < locations.length; i++) {
result.push(
<LocationMarker
key={i}
id={i}
coordinate={locations[i]}
title={locations[i].company}
waitTime={locations[i].wait ? `${locations[i].wait} minutes` : 'Closed'}
onShowModal={() => {
dispatch({
type: 'show_modal', payload: {
companyName: locations[i].company,
companyAddress: locations[i].address,
waitTime: locations[i].wait,
}
});
modalRef.current.open();
}}
/>
)
}
}
return result;
};
return (
<View style={{flex: 1}}>
<Map markers={createMarkers()}/>
{/*<Map ref={modalRef} markers={...createMarkers()} />*/}
<SearchBar style={styles.searchBarStyle}/>
{err ? <View style={styles.errorContainer}><Text
style={styles.errorMessage}>{err.message}</Text></View> : null}
<CheckinModal
ref={modalRef}
businessName={modalState.companyName}
address={modalState.companyAddress}
waitTime={modalState.waitTime}
/>
</View>
);
};
Карта
const Map = ({markers}, ref) => {
const {state: {currentLocation}} = useContext(Context);
return (
<MapView
style={styles.map}
provider={PROVIDER_GOOGLE}
initialRegion={{
...currentLocation.coords,
latitudeDelta: regions.latDelta,
longitudeDelta: regions.longDelta
}}
showsUserLocation
>
{markers ? markers.map((marker, index) => {
return marker;
}): null}
</MapView>
)
};
export default Map;
CheckinModal
const CheckinModal = ({businessName, address, waitTime}, ref) => {
return (
<ModalBox
style={styles.modal}
position={'bottom'}
backdrop={true}
ref={ref}
>
<Text>Store Name: {businessName}</Text>
<Text>Store Address: {address}</Text>
<Text>Wait time: {waitTime} minutes</Text>
</ModalBox>
)
};
const forwardModal = React.forwardRef(CheckinModal);
export default forwardModal;
LocationMarker
const LocationMarker = (props) => {
return (
<View>
<Marker
coordinate={props.coordinate}
title={props.title}
id={props.id}
onPress={() => {
props.onShowModal();
}}
>
<Image
source={require('../../assets/marker2.png')}
style={styles.locationMarker}/>
<View style={styles.waitContainer}>
<Text style={styles.waitText}>{props.waitTime}</Text>
</View>
</Marker>
</View>
)
};
export default LocationMarker;
С этим новым кодом мне больше не нужно пересылать ссылки, только на CheckinModal .
Если у кого-то возникнут вопросы, напишите их под этим ответом, и я постараюсь ответить на них, как только смогу. Спасибо всем за помощь.