首页 > 解决方案 > reactjs中通过数组映射的问题

问题描述

我是 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 存储位置的方式有关,或者是否与其他问题有关。

标签: javascriptreactjsapigoogle-mapses6-promise

解决方案


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

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

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

你也可以参考这篇文章。

何时使用 React setState 回调


推荐阅读