首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >传单w/ render:当this.props更新时,单个国家的颜色不会重新呈现,只有当鼠标超过时才会重新呈现?

传单w/ render:当this.props更新时,单个国家的颜色不会重新呈现,只有当鼠标超过时才会重新呈现?
EN

Stack Overflow用户
提问于 2017-03-20 12:07:23
回答 1查看 814关注 0票数 0

我成功地制作了一个传单地图,其中每个国家的颜色变化取决于我收到的输入作为this.props.data在这个特定的反应组件。

它将正确地显示国家和最初的颜色。然而,这些信息是每分钟从后端输入的。如果this.props.data更新,国家不改变颜色-只有当我拿着鼠标在一个特定的国家,那么颜色实际上会改变?

作为参考,我从一个文件(本质上是一个JS国家数据库)中导入React类中的国家,如下面的示例:http://codepen.io/dagmara223/pen/jydMqy

这是我的源代码。

代码语言:javascript
复制
import React from 'react';
import L from 'leaflet';
import countries from './countries.js';


var Worldmap = React.createClass({

    render: function() {

        if(!this.props.data)
            return <div> loading world map ..  </div>;

        let dataratio = this.props.data; // Props from main component
        let size = Object.keys(dataratio).length; // Do we have data?

        if(size > 1) { // If we do have data, ..

            let dataratioToArr = Object.keys(dataratio).map(data => [ data, dataratio[data]]); // Conv. map to multidimensional array

            let featuresArr = countries.features; // array of all countries in array features from countries.js

            for(let i = 0; i < featuresArr.length; i++) // i = 178(no. of countries)
                for(let j = 0; j < dataratioToArr.length; j++) // j = no. of countries we have with dataratio > 1 from backend
                    if(dataratioToArr[j][0] == featuresArr[i].id) // If ISO-3 compliant ID of country(f.e. "USA") matches, push a "data" property to countries.js
                        featuresArr[i].properties.data = dataratioToArr[j][1];
        }

        return(
            <div id="leafletmap" style={{width: "100%", height: "80%", border: "2px solid black" }} />
        )
    },

    componentDidMount : function() {
        let geolocation =  [];
        // Retrieve geoloc coordinates
        navigator.geolocation.getCurrentPosition(function(position) {
            let lat = position.coords.latitude;
            let lon = position.coords.longitude;

            if(lat != null && lon != null) // If we can get latitude and longitude, reset geolocation and push values.
                geolocation.length = 0;
            geolocation.push(lat, lon);
            if(!lat || !lon) // If we can't get latitude or longitude, set a default value.
                geolocation = [0,0];

            let map = L.map('leafletmap').setView(geolocation, 3); // ([coordinates], zoomlevel)

            let info = L.control();

            info.onAdd = function (map) {
                this._div = L.DomUtil.create('div', 'info');
                this.update();
                return this._div;
            };

            info.update = function (props) {
                this._div.innerHTML = '<h4>Data ratio</h4>' +  (props ?
                    '<b>' + props.name + '</b><br />' + props.data + ' ratio'
                        : 'Hover over a country');
            };

            info.addTo(map);


            function getColor(d) {
                return d > 90 ? '#4a1486' :
                    d > 75  ? '#6a51a3' :
                        d > 50  ? '#807dba' :
                            d > 25  ? '#9e9ac8' :
                                d > 15   ? '#bcbddc' :
                                    d > 5   ? '#dadaeb' :
                                        d > 1   ? '#f2f0f7' :
                                            '#D3D3D3'; // Default color of data doesn't exist or is 0.
            }


            function style(feature) {
                return {
                    weight: 2,
                    opacity: 1,
                    color: 'white',
                    fillOpacity: 1,
                    fillColor: getColor(feature.properties.data)
                };
            }

            function highlightFeature(e) {
                let layer = e.target;

                layer.setStyle({
                    weight: 5,
                    color: '#666',
                    fillOpacity: 0.7
                });

                if (!L.Browser.ie && !L.Browser.opera && !L.Browser.edge) {
                    layer.bringToFront();
                }

                info.update(layer.feature.properties);
            }

            let geojson;

            function resetHighlight(e) {
                geojson.resetStyle(e.target);
                info.update();
            }

            function zoomToFeature(e) {
                map.fitBounds(e.target.getBounds());
            }

            function onEachFeature(feature, layer) {
                layer.on({
                    mouseover: highlightFeature,
                    mouseout: resetHighlight,
                    click: zoomToFeature
                });
            }


            geojson = L.geoJson(countries, { // from import
                style: style,
                onEachFeature: onEachFeature
            }).addTo(map);

            let legend = L.control({position: 'bottomright'});

            legend.onAdd = function (map) {

                let div = L.DomUtil.create('div', 'info legend'),
                    grades = [1, 5, 15, 25, 50, 75, 90],
                    labels = [],
                    from, to;

                for (let i = 0; i < grades.length; i++) {
                    from = grades[i];
                    to = grades[i + 1];

                    labels.push(
                        '<i style="background:' + getColor(from + 1) + '"></i> ' +
                        from + (to ? '&ndash;' + to : '+'));
                }

                div.innerHTML = labels.join('<br>');
                return div;
            };

            legend.addTo(map);
        });

    }
});

export default Worldmap

首先,我将这个componentDidMount作为getInitialState;但是我更改为componentDidMount,因为这应该会在数据更改时触发组件的重新呈现。文档声明If you need to load data from a remote endpoint, this is a good place to instantiate the network request. Setting state in this method will trigger a re-rendering. --这在我的代码中并没有真正发生。也许我误会了?

如果组件从未重新呈现,我可以理解,但是如果某个国家发生了鼠标切换事件(F.E.),这是非常奇怪的。我控制着美国,如果它改变了,颜色值将改变为正确的颜色,但在发生这种情况(或者刷新整个站点)之前是不会的。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-03-20 19:41:13

看起来,您将两个不同的呈现概念混为一谈。当使用React时,它被设计为控制呈现过程;如果引入另一个库来管理呈现,那么您可能会遇到问题。

function是根据以下公式设计的: view = f( data ),换句话说,您的视图是数据的函数。在“反应”中,数据是通过道具或国家表示的。在这种情况下,您不是使用React来管理道具或状态,而是使用“传单”。您需要决定是使用React还是使用传单来控制呈现,然后再使用它。在这种情况下,考虑到它有自己的呈现和管理交互的API,最好把所有的事情都留给传单。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42903172

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档