【问题标题】:reactjs gives me this error: TypeError: this.state.coords.map is not a functionreactjs 给了我这个错误: TypeError: this.state.coords.map is not a function
【发布时间】:2021-03-26 14:45:41
【问题描述】:

这是我的代码:

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"] 并尝试使用它进行 map 并且它有效

【问题讨论】:

  • 您将 coords 设置为一个没有 map 方法的对象。 this.setState({coords:CoordsObj})
  • @pilchard 谢谢你的来信

标签: javascript arrays reactjs function dictionary


【解决方案1】:
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 中的代码

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2022-01-01
      • 1970-01-01
      • 2019-01-30
      • 2022-12-15
      • 2019-01-10
      • 2020-04-24
      • 2015-05-04
      • 2018-07-23
      • 1970-01-01
      相关资源
      最近更新 更多