【问题标题】:Issue in mapping through array in reactjsreactjs中通过数组映射的问题
【发布时间】:2020-08-24 01:50:17
【问题描述】:

我是 ReactJs 的新手。我的项目正在从我的后端获取数据,其中包含一个 Cell Id,然后将该 Cell Id 发送到另一个 api 并接收 Cell ID 的纬度和经度。为此,我必须存储每个单元格 ID 的位置。看来我可以将纬度和经度存储在 this.state.loc 中。但是,当通过该数组映射以在地图上放置标记时,我遇到了一个问题。在第一个代码块中,当我尝试将位置的纬度记录到控制台时,它只记录其中一个。


import React, {Component,useState, useEffect} from 'react';
import './App.css';
import {GoogleMap, withScriptjs, withGoogleMap, Marker, useLoadScript, InfoWindow} from "react-google-maps";







class App extends Component {
  
    constructor(props) {
        super(props);
        this.state = {
        users: [],
        loc:[{}]
        
            
        };
    }
    

  
    
  
    
   componentDidMount() {
    
        fetch('/users')
        .then(res=>res.json())
        .then(users=>this.setState({users}))
        .then(users=>this.state.users.map(user => {
                 
                                              
                                
            var num = user.CallingCellID
            if(num != null) {
                                                                                  
                                                                                  
                                var digits = (num).toString().split('');
                                var realDigits = digits.map(Number);
                                var mcc = 419;
                                var mnc = 4;
                                                                                  
                                var lac = (realDigits[6]*1000) + (realDigits[7]*100) + (realDigits[8]*10) + (realDigits[9]*1);
                                var cid = (realDigits[10]*10000)+ (realDigits[11]*1000) + (realDigits[12]*100) + (realDigits[13]*10) + (realDigits[14]*1);
                                fetch("https://api.mylnikov.org/geolocation/cell?v=1.1&data=open&mcc=419&mnc=4&lac="+lac+"&cellid="+cid)
                                .then(response => response.json())
                                .then(result=> {
                                const locations = result.data;
                                      
                                if(locations.lat != undefined) {
                                      
                                var x = [{lat: locations.lat, lng: locations.lon}];
                                      
                                Promise.all(x).then(data => {this.setState({ loc: data })})
                                      
                                }
                                                                                        
                                                                                        
                                });
                                                                                  
                                                                                  
                                                                                  
                }
          }));
    }
    
                                              

    
    
    
  
    
    
    render() {

        const MyMapComponent = withScriptjs(withGoogleMap((Map) =>
                            <GoogleMap defaultZoom={2} defaultCenter={{ lat: -34.397, lng: 150.644 }}>
                                   {this.state.loc.map(l=>console.log(l.lat))}                     
                                                          
                                </GoogleMap>))

 
        

    return (
            
            <div className="App">
            <header className="App-header">
            <form>
            <label for="Location Search"> Location Search: </label>
            <input type = "text" id = "Location Search" name = "Location Search"/>
            
            <label for="Account Search"> Account Search: </label>
            <input type = "text" id = "Account Search" name = "Account Search"/>
            <label for="IMSI Search"> IMSI Search: </label>
            
            <select id="IMSI Search" name="IMSI">

           <option value="1">1</option>)
            </select>
            
            <label for="IMSI RANGE:"> IMSI RANGE </label>
        
            <input type = "text" id = "IMSI RANGE" name = "IMSI RANGE"/>
            <input type = "text" id = "IMSI RANGE2" name = "IMSI RANGE2"/>
            
            
            </form>
            
            <div id = "googlemap">
            
            <MyMapComponent
            isMarkerShown
            googleMapURL="https://maps.googleapis.com/maps/api/js?key=AIzaSyCa3cfZfuFgpKPUWpXZv7WejZ7u_093A3s"
            loadingElement={<div style={{ height: `800px` }} />}
            containerElement={<div style={{ height: `1500px` }} />}
            mapElement={<div style={{ height: `800px` }} />}
            />
       
          
            
            </div>
            
           
            
          
            
            
            
            
            </header>
            </div>
            
            );
    
    }
    
}

export default App;



但是在下面的代码块中,当我将 loc 的地图函数移到 myMapComponent 之外,并且就在 render() 下方时,它成功地将纬度记录到控制台。

 render() {
{this.state.loc.map(l=>console.log(l.lat))}   
        const MyMapComponent = withScriptjs(withGoogleMap((Map) =>
                            <GoogleMap defaultZoom={2} defaultCenter={{ lat: -34.397, lng: 150.644 }}>
                                                     
                                                          
                                </GoogleMap>))

我是新手,所以我不确定是什么问题。我不确定这是否与我为每个 Cell ID 存储位置的方式有关,或者是否是其他问题。

【问题讨论】:

    标签: javascript reactjs api google-maps es6-promise


    【解决方案1】:

    您将不得不使用回调函数,因为在调用之后 setState ,数据可能不会立即更新使用。

    你需要像这样传递一个回调函数

    this.setState({users}, () => {
    **Do your this.state.users.map **
    })
    

    你也可以参考这篇文章。

    When to use React setState callback

    【讨论】:

    • 嗨@KevinMoeMyintMyat,我的代码看起来像.then(res=&gt;res.json()) .then(users=&gt;this.setState({users}, () =&gt; {**this.state.users.map })。我忘了提及这一点,但是当我的console.log()MyMapComponent 之外时。每个纬度都被记录到控制台两次。我也不知道为什么会这样。
    • @DeyvikBhan 您现在的问题是 state.loc 只有一个位置而不是多个位置?我认为这是因为您在每次迭代中都设置了一个状态。您需要做的是在 .map 迭代之前和循环期间在外部声明一个 empy 数组,将结果推入内部。在所有循环之后,使用该数组的 setState 。此外,在这种情况下,我更喜欢 .forEach 而不是 .map
    • 嗨@KevinMoeMyintMyat 感谢您的回复。我实现了它,当我执行 console.log(my.state.loc) 时,它返回一个像 [{....}] 这样的对象,当我单击展开它时,它在控制台中返回它。 0: {} ,1: [{...}], 2:[{...}]。同样,我无法使用我在上面的代码中使用的映射方法来映射它。是否有不同的方法来映射它,或者我得到的结果格式错误?
    • @DeyvikBhan 我可以获取示例 api 调用和响应吗?我尝试了api.mylnikov.org/geolocation/…,但得到了 Object is not found 错误。对于 lac 和 cellid 值,您使用了什么?
    • 您好,很抱歉回复晚了。为了获得正确的输出数组,我没有在迭代之外设置状态,而是在this.state.users 的最后一次迭代中设置状态。
    猜你喜欢
    • 2017-04-09
    • 2018-06-13
    • 1970-01-01
    • 2017-12-26
    • 2020-08-14
    • 1970-01-01
    • 1970-01-01
    • 2020-04-22
    • 1970-01-01
    相关资源
    最近更新 更多