簡體   English   中英

在 React Child 中通過數組訪問 Map 的道具?

[英]Accessing Props to Map over Array in React Child?

一直在使用 react 並仍在嘗試掌握所有概念。 可以使用幫助來了解我如何使它工作。 我想將數組作為道具傳遞給 map 的另一個反應組件。 有人可以指出我在這里做錯了什么嗎? 我可以通過陣列 map 作為 function 但不能在內部渲染:

應用程序.js

import React, { Component } from 'react';
import Leaf from './components/Leaf';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      viewport: {
        height: "100vh",
        width: "100vw",
        latitude: 40.7128,
        longitude: -74.0060,
        zoom: 10
      },
      latitude: 40.7128,
      longitude: -74.0060,
      zoom: 10,
      stations: [],
      selectedStation: null,
      userLocation: {}
    };
  }

  componentDidMount() {
    fetch('https://gbfs.citibikenyc.com/gbfs/en/station_information.json')
    .then(res => res.json())
    .then(res=>
      this.setState({stations: res}))
  }

  checkData=()=>{
    console.log(this.state.stations)
    this.state.stations.data.stations.map(e=>{
      console.log(e)
    })
  }

  render() {

    return (
      <div>
          <button onClick={this.checkData}>click me</button>   
          <Leaf 
            viewport={this.state.viewport}
            stations={this.state.stations}/>
      </div>
    );
  }
}

export default App;

葉.js

import React, {Component} from 'react';
import { Map, TileLayer, Marker, Popup } from 'react-leaflet';
import { Button } from 'react-bootstrap';

class leaf extends Component {

    checkData=()=>{
        this.props.stations.data.stations.map(e=>{
          console.log(e)
        })
      }



    render() {

        const markers = this.props.stations.data.stations.map((station) =>
        <Marker 
          position={[station.lat, station.lon]}
          onClick={this.markerClick.bind(this,station)}>
          <Popup>
          </Popup>
        </Marker>
              );


        const position = [this.props.viewport.latitude, this.props.viewport.longitude]
        //const position = [40.7484, -73.9857]
        return (
            <div>
                <button onClick={this.checkData}>check props</button>
                <Map center={position} zoom={14}>
                    <TileLayer
                        attribution='&amp;copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
                        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
                    />
                    {markers}
                    <Marker position={position}>
                        <Popup>
                            A pretty CSS3 popup. <br /> Easily customizable.
                        </Popup>
                    </Marker>
                </Map>  
            </div>
        );
    }
}

export default leaf;

在過去,我做過類似的事情:

const Search = ( props ) => {
return (
)
}

但我希望了解如何使用class leaf extends Component來完成這項工作。 感謝幫助。

供參考的數據結構

    {
    last_updated: 1572631066,
    ttl: 10,
    data: {
    stations: [
    {
    station_id: "237",
    external_id: "66db3c29-0aca-11e7-82f6-3863bb44ef7c",
    name: "E 11 St & 2 Ave",
    short_name: "5746.04",
    lat: 40.73047309,
    lon: -73.98672378,
    region_id: 71,
    rental_methods: [
    "CREDITCARD",
    "KEY"
    ],
    capacity: 39,
    rental_url: "http://app.citibikenyc.com/S6Lr/IBV092JufD?station_id=237",
    electric_bike_surcharge_waiver: false,
    eightd_has_key_dispenser: false,
    eightd_station_services: [
    {
    id: "e73b6bfb-961f-432c-a61b-8e94c42a1fba",
    service_type: "ATTENDED_SERVICE",
    bikes_availability: "UNLIMITED",
    docks_availability: "NONE",
    name: "Valet Service",
    description: "Citi Bike Station Valet attendant service available",
    schedule_description: "",
    link_for_more_info: "https://www.citibikenyc.com/valet"
    }
    ],
    has_kiosk: true
    },
    {
    station_id: "281",
    external_id: "66db5fae-0aca-11e7-82f6-3863bb44ef7c",
    name: "Grand Army Plaza & Central Park S",
    short_name: "6839.10",
    lat: 40.7643971,
    lon: -73.97371465,
    region_id: 71,
    rental_methods: [
    "CREDITCARD",
    "KEY"
    ],
    capacity: 66,
    rental_url: "http://app.citibikenyc.com/S6Lr/IBV092JufD?station_id=281",
    electric_bike_surcharge_waiver: false,
    eightd_has_key_dispenser: true,
    eightd_station_services: [
    {
    id: "32461582-cd1e-4ecf-a5ea-563593fa7009",
    service_type: "ATTENDED_SERVICE",
    bikes_availability: "UNLIMITED",
    docks_availability: "NONE",
    name: "Valet Service",
    description: "Citi Bike Valet Attendant Service Available",
    schedule_description: "",
    link_for_more_info: "https://www.citibikenyc.com/valet"
    }
    ],
    has_kiosk: true
    }
]
}
}

嘗試

所以在這里我更改了 const 標記以反映來自 checkData 的 conosle.log:

const markers =  this.props.stations.data.stations.map((station) =>
        <Marker 
          position={[station.lat, station.lon]}
          onClick={this.markerClick.bind(this,station)}>
          <Popup>
          </Popup>
        </Marker>
              );

我收到以下錯誤:

TypeError:無法讀取未定義的屬性“站”

當我刪除標記變量並單擊 checkData 時,請注意它沒有問題映射和控制台記錄 object:

在此處輸入圖像描述

我會仔細檢查您是否訪問了正確的數據屬性,就像在 function 中一樣,您正在調用this.props.stations.data.stations.map ,但在渲染中您正在調用this.props.stations.data.map ,所以一個肯定是不正確的。

此外, class 組件應該是PascalCase ,即大寫。

Camilo 是正確的,我需要確保數據可用於渲染。 下面是工作代碼:

應用程序.js

//import logo from './logo.svg';
//import './App.css';

import React, { Component } from 'react';
import Leaf from './components/Leaf';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      viewport: {
        height: "100vh",
        width: "100vw",
        latitude: 40.7128,
        longitude: -74.0060,
        zoom: 10
      },
      latitude: 40.7128,
      longitude: -74.0060,
      zoom: 10,
      stations: [],
      showStations: false,
      selectedStation: null,
      userLocation: {}
    };
  }

  componentDidMount() {
    const request = async()=> {
      await fetch('https://gbfs.citibikenyc.com/gbfs/en/station_information.json')
      .then(res => res.json())
      .then(res=>
        this.setState({stations: res, showStations: true}))
    }
    request();
  }

  checkData=()=>{
    console.log(this.state.stations)
    this.state.stations.data.stations.map(e=>{
      console.log(e)
    })
  }

  render() {

    return (
      <div>
          <button onClick={this.checkData}>click me</button>   
          <Leaf 
            viewport={this.state.viewport}
            stations={this.state.stations}
            showStations={this.state.showStations}/>
      </div>
    );
  }
}

export default App;

Leaf.js

import React, {Component} from 'react';
import { Map, TileLayer, Marker, Popup } from 'react-leaflet';
//import './leaf.css'
//import InfoBox from './InfoBox';
import { Button } from 'react-bootstrap';
//import Search from './Search';
//import Match from './Match';
//import Modal from './Modal';
//import L from 'leaflet';
//import Routing from "./RoutingMachine";
//import { Row, Col, Grid, Container } from 'react-bootstrap';
//import ErrorBoundary from '../ErrorBoundary/ErrorBoundary'



class Leaf extends Component {


    checkData=()=>{
        this.props.stations.data.stations.map(e=>{
          console.log(e)
        })
      }

    render() {

        let markers =null;
        if(this.props.showStations) {
        markers = (
            <div>
            {
            this.props.stations.data.stations.map((station) =>
                <Marker 
                    position={[station.lat, station.lon]}>
                </Marker>
                )
            }
            </div>
        )
        }


        const position = [this.props.viewport.latitude, this.props.viewport.longitude]
        //const position = [40.7484, -73.9857]
        return (
            <div>
                <button onClick={this.checkData}>check props</button>
                <Map center={position} zoom={14}>
                    <TileLayer
                        attribution='&amp;copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
                        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
                    />
                      {markers}
                    <Marker position={position}>
                        <Popup>
                            A pretty CSS3 popup. <br /> Easily customizable.
                        </Popup>
                    </Marker>
                </Map>  
            </div>
        );
    }
}

export default Leaf;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM