javascript - reactjs 给了我这个错误: TypeError: this.state.coords.map is not a function
问题描述
这是我的代码:
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"] 并尝试使用它进行映射并且它有效
解决方案
尝试将值推送到您的数组。
position = (location) => {
let CoordsObj = [{
latitude: location.coords.latitude,
longitude: location.coords.longitude,
}]; //Note the array []
this.setState({coords:CoordsObj})
}
推荐阅读
- swift - 从呈现为字符串的 JSON 解析十进制
- java - Spring-boot mongoTemplate如何在mongoDB中找到具有最大值的实体
- java - 以编程方式将侦听器设置为 CheckBox 数组
- html - 当我在页脚中使用位置修复时,如何填充我的内容包装器 div?
- angular - 我可以在 Angular 7 中向“窗口”对象添加属性吗?
- django - 在 Django 中使用 id 进行多对多反向字段查找 | 多态模型
- rest - Spring REST Docs - 未记录的部分:
- sql - 如何在mongodb中查找重复记录数
- django - 如何从我的 Django 网页下载内容?
- python-3.x - 如何读取大 csv 文件并分别读取每一列?