这是我的代码:
import React, { Component } from 'react';
class SeasonApp extends Component {
constructor(props){
super(props)
this.state = {
coords:[],
error:[],
}
}
position = (location) => {
let CoordsObj = {
latitude: location.coords.latitude,
longitude: location.coords.longitude,
}
this.setState({coords:CoordsObj})
}
err = (err) => {
let errorObj = {
error:err.message,
}
this.setState({error:errorObj})
}
getLoction = () => {
window.navigator.geolocation.getCurrentPosition(this.position,this.err)
}
render() {
return (
<React.Fragment>
<button onClick={this.getLoction}>Get Location</button>
{this.state.coords.map(item => { //problem starts from here
return(
<div>
<h2>{item.longitude}</h2>
</div>
)
})}
<h1>error: {this.state.error.error}</h1>
</React.Fragment>
);
}
}
export default SeasonApp;
<块引用>
列表项
我的代码在没有地图功能的情况下工作正常,我不明白错误。 我在状态测试中创建了一个新数组:["a","b","c"] 并尝试用它映射并且它工作了
答案 0 :(得分:0)
尝试将值推送到您的数组中。
position = (location) => {
let CoordsObj = [{
latitude: location.coords.latitude,
longitude: location.coords.longitude,
}]; //Note the array []
this.setState({coords:CoordsObj})
}
答案 1 :(得分:0)
position = (location) => {
let CoordsObj = {
latitude: location.coords.latitude,
longitude: location.coords.longitude,
}
this.setState({coords:CoordsObj})
}
在这里,您已将 coords
设为一个对象。它不再是数组,因此无法映射。如果您需要它是一个数组,请执行以下操作:
position = (location) => {
let CoordsObj = {
latitude: location.coords.latitude,
longitude: location.coords.longitude,
};
let temp_coords = [...this.state.coords];
temp_coords.push(CoordsObj);
this.setState({ coords: temp_coords });
};
或者,更改您的 jsx