英文:
How to use latitude and longitude anywhere in the program in React
问题
你需要在<Map>标签中的center属性中使用地理数据。但是React禁止在HTML块中使用JavaScript代码。我尝试从Promise中获取数据,但始终得到undefined。
function App() {
var lc;
var getLocationPromise = new Promise((resolve) => {
navigator.geolocation.getCurrentPosition(async function (position) {
resolve([position.coords.latitude, position.coords.longitude])
})
})
getLocationPromise.then((location) => {
lc = location
return lc
}).catch((err) => {
document.white("error")
})
return (
<YMaps>
<Map className="myMap" defaultState={{ center: [34, 55], zoom: 9 }}></Map>
</YMaps>
)
}
export default App;
英文:
You need to use the geodata in the <Map> tag, in the center attribute. But React prohibits the use of js code in a block with html. I tried to pull data from promise, but I always got undefined.
function App() {
var lc;
var getLocationPromise = new Promise((resolve) => {
navigator.geolocation.getCurrentPosition(async function (position) {
resolve([position.coords.latitude, position.coords.longitude])
})
})
getLocationPromise.then((location) => {
lc = location
return lc
}).catch((err) => {
document.white("error")
})
return (
<YMaps>
<Map className="myMap" defaultState={{ center: [34, 55], zoom: 9 }} ></Map>
</YMaps>
</div>
)
}
export default App;
答案1
得分: 0
你可以使用如下所示的 React 本地状态:
const [lat, setLat] = React.useState(0);
const [lng, setLng] = React.useState(0);
getLocationPromise.then((location) => {
setLat(location[0]);
setLng(location[1]);
}).catch((err) => {
document.write("error");
})
<Map className="myMap" defaultState={{ center: [lat, lng], zoom: 9 }}></Map>
英文:
You may use react local state as shown below
const [lat, setLat] = React.useState(0);
const [lng, setLng] = React.useState(0);
getLocationPromise.then((location) => {
setLat(location[0]);
setLng(location[1]);
}).catch((err) => {
document.write("error")
})
<Map className="myMap" defaultState={{ center: [lat, lng], zoom: 9 }} ></Map>
答案2
得分: 0
你尝试使用 useEffect 钩子了吗?你应该能够在任何地方引用对象(如果这是你想要做的话),使用 React 的 "useEffect" 和 "useState" 属性。
对于你的用例,你应该像这样做:
const [geoData, setGeoData] = useState(null)
useEffect(async () => {
const data = await YOUR_FUNCTION() // Promise
setGeoData(data)
},
// 这个应该是空的
[])
然后在你的代码中,你可以访问 geoData 并按照你的需求使用它。
英文:
Did you try useEffect hook ?
You should be able to reference the object from anywhere (if thats what you want to do) with React's "useEffect"and "useState" properties.
For your usecase, you should do something like this:
const [geoData, setGeoData] = useState(null)
useEffect(async ()=>{
const data = await YOUR_FUNCTION() / Promise
setGeoData(data)
},
// This one should be empty
[])
and then in your code, you can access the geoData and use it as you want.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论