首页 > 解决方案 > 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"] 并尝试使用它进行映射并且它有效

标签: javascriptarraysreactjsfunctiondictionary

解决方案


尝试将值推送到您的数组。

position = (location) => {
        let CoordsObj = [{
            latitude: location.coords.latitude,
            longitude: location.coords.longitude,
        }]; //Note the array []
        this.setState({coords:CoordsObj})
    }


推荐阅读