反应componentDidMount()影响渲染

时间:2018-08-16 12:09:24

标签: reactjs lifecycle openlayers-5

我从“应用程序组件”状态设置“面板组件”的属性。当我单击按钮时,我想增加(示例)地图坐标。可以,但是我必须在Panel的componentDidMount()中声明openlayers变量,但是一旦运行,componentDidMount就会运行,因此坐标不会更改地图我该怎么办 ?请帮助...。

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Panel from './Map'


class App extends Component {
  constructor() {
    super();
    this.state = {
      coordinates: [46.41, 40.82]
    }
  }
  render() {

    return (
      <div >
        <Panel coordinates={this.state.coordinates} />
        <div><button onClick={() => {
          this.setState({
            coordinates: [this.state.coordinates[0] + 1, this.state.coordinates[1]]
          })
        }}>Go</button></div>
      </div>
    );
  }
}

export default App;

面板组件

import React from 'react'
import 'ol/ol.css';
import { Map, View } from 'ol';
import TileLayer from 'ol/layer/Tile';
import OSM from 'ol/source/OSM';
import proj from 'ol/proj/';
import { fromLonLat } from 'ol/proj';

export default class Panel extends React.Component {

    constructor() {
        super();
        this.state = {
            crd: [46, 40]
        }
    }
    GetCoordinates() {
        return this.state.crd
    }

    componentWillReceiveProps(prp) {
        this.setState({ crd: prp.coordinates })
    }
    componentDidMount() {
        const map = new Map({
            target: 'map',
            layers: [
                new TileLayer({
                    source: new OSM()
                })
            ],
            view: new View({
                center: fromLonLat(this.GetCoordinates()) // i need set here,
                zoom: 7
            })
        });
    }
    render() {
        return <div id="map" style={{ width: '700px', height: '500px' }}></div>
    }
}

1 个答案:

答案 0 :(得分:0)

开放层具有命令性API,这意味着您必须调用map对象上的方法来对其进行更新。

因此,当您在componentDidMount中实例化地图时,首先需要保留其地图参考:

componentDidMount() {
    this.map = new Map({
        target: 'map',
        layers: [
            new TileLayer({
                source: new OSM()
            })
        ],
        view: new View({
            center: fromLonLat(this.GetCoordinates()) // i need set here,
            zoom: 7
        })
    });
}

然后在componentWillReceiveProps中,您必须在更改状态后“命令”地图以更新地图中心:

componentWillReceiveProps(prp) {
    this.setState({ crd: prp.coordinates }, function() {
        this.map.getView().setCenter(ol.proj.fromLonLat(this.GetCoordinates()));
    });
}

请注意,此处您的组件无需将坐标保持在其状态。您可以使用普通实例变量来存储坐标,并避免由setState引起的不必要的渲染:

....
constructor() {
    super();
    this.crd = [46, 40];
}
GetCoordinates() {
    return this.crd
}
componentWillReceiveProps(prp) {
    this.crd = prp.coordinates;
    this.map.getView().setCenter(
        ol.proj.fromLonLat(this.GetCoordinates())
    );
}
....