[英]Using leaflet and need to update component. How can I update the values in my constructor?
我在我的react組件中使用傳單,並且正在使用scriptLoading庫加載所有必要的腳本。
我的構造函數中包含以下內容:
constructor(props) {
super(props);
this.map = null;
this.popup = null;
}
我正在像這樣加載傳單:
componentWillReceiveProps({ isScriptLoaded, isScriptLoadSucceed }) {
if (isScriptLoaded && !this.props.isScriptLoaded) {
if (isScriptLoadSucceed) {
this.map = L.map(this.refs.map);
///////
this.popup = L.popup();
///////
但是,我的類中有一個處理onClickMap(e)
的函數, this.map
和this.popup
始終為null。 在我的渲染函數中, this.map
和this.popup
不為null。
onClickMap(event) {
console.log('on click', this.popup, this.map); // both null
if (this.popup) {
this.popup
.setLatLng(event.latlng)
.setContent('You clicked the map at ' + event.latlng.toString())
.openOn(this.map);
}
}
如何正確更新構造函數值?
在構造函數中使用this.state
。
constructor(props) {
super(props);
this.state = {
map: null,
popup: null
}
}
並在componentWillReceiveProps中使用setState
。
componentWillReceiveProps({ isScriptLoaded, isScriptLoadSucceed }) {
if (isScriptLoaded && !this.props.isScriptLoaded) {
if (isScriptLoadSucceed) {
this.setState({
map: L.map(this.refs.map),
popup: L.popup()
});
///////
您可以從this.state
獲取它。
onClickMap(event) {
console.log('on click', this.state.popup, this.state.map); // both null
if (this.state.popup) {
this.state.popup
.setLatLng(event.latlng)
.setContent('You clicked the map at ' + event.latlng.toString())
.openOn(this.state.map);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.