使用 React Native Expo,我有一個 MapView 螢屏,它在底部螢屏上顯示標記(標題、描述、影像等)的資訊。目前我有一個函式,當按下標記時,標記資訊將傳遞給名為 MarkerInfo 的變數并顯示在底部螢屏上。但是,當組件初始化時,底表中不顯示任何資訊。
我想顯示一條訊息,提示用戶選擇標記。
這是包含 pressMarker 函式的當前代碼塊:
// ## Attempting to set intial values prompting users to select a marker for more info
const state = {
MarkerInfo: {
PreviewTitle: "Select A Marker.",
Description: "Press on a marker to get location information"
}
};
// ## Without the code above this all works fine:
// ## Setting the currently selected marker as variable (in an array) "MarkerInfo".
const [MarkerInfo, setMarkerInfo] = useState([]);
const pressMarker = (i) => {
setMarkerInfo(i);
console.log(i)
return(MarkerInfo)
};
下面是標記資訊陣列的示例,當標記被按下時。
Object {
"Description": "Former historic palace housing huge art collection, from Roman
sculptures to da Vinci's 'Mona Lisa.",
"ImageUrl": "*** My firebase storage URL",
"Latitude": 48.86074344,
"Location": "Paris",
"Longitude": 2.337659481,
"PreviewTitle": "Louvre",
"Title": "Louvre Museum",
"id": 64,
"key": "63",
}
然而,在我擊中標記之前,底部作業表什么也不顯示。所以看起來我對 Marker info 的初始變數定義沒有像我希望的那樣執行。
我需要對初始宣告進行哪些更改?我也嘗試過使用 component did mount 做一個函式,并沒有運氣回傳初始標記資訊。
uj5u.com熱心網友回復:
您不需要像componentDidMount使用鉤子那樣使用生命周期方法。當您使用 React 建議的鉤子和功能組件時,您首先嘗試初始化狀態的方式似乎是錯誤的。
當您從陣列中選擇一個專案時,您必須傳遞與您將在狀態上擁有的物件相同的物件,作為useState宣告中的初始值。
所以你的代碼應該是
const initialState = {
"Description": "Press on a marker to get location information",
"ImageUrl": "",
"Latitude": 0,
"Location": "",
"Longitude": 0,
"PreviewTitle": "Select A Marker.",
"Title": "Select A Marker.",
"id": 0,
"key": "",
}
const [MarkerInfo, setMarkerInfo] = useState(initialState);
ps 我假設您的 PreviewTitle 和 Description 是您在螢屏上顯示的那個
uj5u.com熱心網友回復:
嘗試使用
setMarkerInfo([...i]);
而是使用
setMarkerInfo(i);
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/315556.html
標籤:javascript 反应原生 世博会 状态 使用状态
