遇到坑的介绍
我在调用百度地图时,打算点击mark时,触发操作组件的其他函数,但是提示函数无法找到
import React, {Component} from 'react';
import styles from './index.less'
import {connect} from "dva";
@connect(({ apdistribution }) => ({apdistribution}))
class MyMap extends Component{
constructor(props) {
super(props);
}
componentDidMount() {
this.renderChart();
}
componentDidUpdate(prevProps) {
const update = this.compareProps(prevProps, this.props);
/* 再优化 */
if(update){
this.reRenderChart(this.props)
}
}
// 比较前后参数是否相同
compareProps = (oldProps={}, newProps={}) =>{
const oldPropsString = JSON.stringify(oldProps);
const newPropsString = JSON.stringify(newProps);
return ! (oldPropsString === newPropsString);
};
// 第二次渲染百度地图
reRenderChart = props =>{
const{apdistribution:{aps}} = this.props;
this.makeMap(aps)
};
// 第一次渲染百度地图
renderChart = () =>{
const{apdistribution:{aps}} = this.props;
this.makeMap(aps)
};
makeMap=(aps)=>{
const that = this;
if(aps!== undefined) {
const map = new BMap.Map("myMap");
map.setMapType(BMAP_HYBRID_MAP)
map.addControl(new BMap.MapTypeControl({
mapTypes: [
BMAP_HYBRID_MAP,
BMAP_NORMAL_MAP,
]
}
));
const point = new BMap.Point(120.487295, 36.126442);
map.centerAndZoom(point, 15);
map.enableScrollWheelZoom(true);//开启鼠标滚轮缩放
// 编写自定义函数,创建标注
function addMarker(point,ap) {
const marker = new BMap.Marker(point);
map.addOverlay(marker);
marker.addEventListener("click", function (e) {
alert("您点击了标注"+ap.lys)
# this.showModal(ap);
# 直接提示找不到函数
#使用that问题解决
that.showModal(ap);
})
}
for (let i = 0; i < aps.length; i++) {
const jwd=aps[i].jwd.split(',');
const point1 = new BMap.Point(parseFloat(jwd[0]),parseFloat(jwd[1]));
addMarker(point1,aps[i]);
}
}
}
// 调用此处的函数
showModal = (ap) => {
const {dispatch} = this.props;
dispatch({
type: 'apdistribution/SetApStudentsModalVisible',
payload:{apStudentsModalVisible:true}
});
};
render(){
const{apdistribution:{aps}} = this.props;
console.log(aps);
if(this.map){
this.makeMap(aps);
}
return (
<div className={styles.myPage}>
<div id='myMap' className={styles.map}></div>
我的地图
</div>
)
}
}
export default MyMap;
问题分析
在javascript中,this代表的是当前对象。
var that=this就是将当前的this对象复制一份到that变量中。这样做有什么意义呢?
$('#lys').click(function(){
//this是被点击的#lys
var that = this;
$('.lys').each(function(){
//this是.lys循环中当前的对象
//that仍然是刚才被点击的#lys
});
});
可以看到,this对象在程序中随时会改变,而var that=this之后,that没改变之前仍然是指向当时的this,这样就不会出现找不到原来的对象。