【发布时间】:2021-01-26 02:51:26
【问题描述】:
我在读取子组件的 componentDidMount() 挂钩中的道具值时遇到了一些问题
我可以在子组件本身中引用它们,但在钩子内部它们显示为未定义:(
希望有人可以在这里为我指明正确的方向......对于奇怪的组件,使用 arcgis api 和 npm esri-loader 感到抱歉
APP.js
import React, { Component } from 'react'
import './App.css';
import {WebMapView} from './components/map.js'
import { RiEarthquakeLine } from 'react-icons/ri';
import { RiFloodLine } from 'react-icons/ri';
import { AiOutlineFire } from 'react-icons/ai';
export default class App extends Component {
constructor(props){
super(props)
this.state={
fire: "on",
flood: "off",
quakes: "off"
}
this.toggled = this.toggled.bind(this)
}
toggled(e){
console.log("inside toggled",e.target.id)
}
render() {
return (
<div className="App">
<header className="App-header"> </header>
<div className="leftMenu">
<div className="nav">
<ul className="toggleopts">
<li id="quake" onClick={this.toggled} className="toggleicon"><RiEarthquakeLine /></li>
<li id="flood" onClick={this.toggled} className="toggleicon"><RiFloodLine/></li>
<li id="fire" onClick={this.toggled} className="toggleicon"><AiOutlineFire/></li>
</ul>
</div>
<div className="EsriMapContainer">
<WebMapView props={this.state} />
</div>
</div>
</div>
)
}
}
子组件
import React from 'react';
import { loadModules } from 'esri-loader';
export class WebMapView extends React.Component {
constructor(props) {
super(props);
this.mapRef = React.createRef();
}
componentDidMount() {
var props = this.props
// lazy load the required ArcGIS API for JavaScript modules and CSS
loadModules(['esri/Map', 'esri/views/MapView',"esri/widgets/Search","esri/layers/FeatureLayer"], { css: true },props)
.then(([ArcGISMap, MapView, Search, FeatureLayer],props) => {
console.log(this.props) //undefined here
const map = new ArcGISMap({
basemap: 'dark-gray'
});
this.view = new MapView({
container: this.mapRef.current,
map: map,
center: [-118, 34],
zoom: 10
});
if(props.flood===false){
var floodHazards = new FeatureLayer({
url:
"https://services9.arcgis.com/RHVPKKiFTONKtxq3/arcgis/rest/services/USA_Wildfires_v1/FeatureServer"
});
map.add(floodHazards);
}
if(props.fire==true){
var fireAOE = new FeatureLayer({
url:
"https://earthobs1.arcgis.com/arcgis/rest/services/Live_Stream_Gauges/MapServer"
});
map.add(fireAOE);
}
if(props.quakes===false){
var quakes = new FeatureLayer({
url: "https://services1.arcgis.com/VAI453sU9tG9rSmh/arcgis/rest/services/Major_Earthquakes_features/FeatureServer"
})
map.add(quakes)
}
var search = new Search({
view: this.view
});
this.view.ui.add(search, "top-right");
});
}
componentWillUnmount() {
if (this.view) {
// destroy the map view
this.view.destroy();
}
}
render() {
return (
<div className="webmap" ref={this.mapRef} />
);
}
}
【问题讨论】:
标签: javascript reactjs react-props