React组件(GeoJSON)不会在状态更改时重新呈现

时间:2019-01-02 22:57:33

标签: javascript json reactjs geojson react-leaflet

我使用react-leaflet库创建一个简单的地理门户,用户可以在其中更改矢量层的颜色,可见性和透明度。我使用了滑块来更改React颜色集合中的颜色。问题在于,在使用GeoJSON更改组件状态中的样式后,矢量层不会更改其颜色-它不会再次呈现。

这是我的带有GeoJSON层的组件(可能由于反复尝试解决此问题而导致一些不必要的元素):

import React from 'react';
import PropTypes from 'prop-types';
import { GeoJSON } from 'react-leaflet';

class VectorLayers extends React.Component{
    constructor(props){
        super(props);
        this.state={
            key: this.props.layer.name,
            data: this.props.layer,
            style: {
                weight: 0,
                fillColor: this.props.color,
                fillOpacity: this.props.color,
                styleChanged: false
            },
        }
    }

    componentDidUpdate(prevProps, prevState) {
        if(this.state.style !== prevState.style) {
            let newStatus = !this.state.style.styleChanged
            this.setState({newStatus})
        }
    }

    static getDerivedStateFromProps(nextProps, prevState){
        if(nextProps.color!==prevState.style.fillColor){
            return {style: {
                weight: 0,
                fillColor : nextProps.color,
                fillOpacity : nextProps.color
            }}
        }
        else return null;
    }
    render(){
        return (
            <GeoJSON
                key={ this.state.key }
                data={ this.state.data }
                style={ this.state.style }
            />
        );
    }
}

VectorLayers.propTypes = {
    layer: PropTypes.shape().isRequired,
    color: PropTypes.string.isRequired
};

export default VectorLayers;

这是我的App.js代码的一部分,其中包含用于矢量层的道具:

            {
                this.state.layers.map((layer) => ( 
                    this.state.checkboxes[layer.name] && (
                        <VectorLayers
                            key={ layer.name }
                            layer={ layer }
                            color={ this.state.colors[layer.name] }
                        />
                    )
                ))
            }

使用滑块更改颜色和组件的功能效果很好,因此我看不到需要在此处添加它们的功能。我将非常感谢您在寻找解决方案方面的帮助!

1 个答案:

答案 0 :(得分:0)

编辑:将样式更改为如下功能:

style={() => {return ({fillColor: this.state.style.fillColor})}}

看起来您使用的密钥永远不会改变,因此react不会麻烦您重新渲染GeoJSON。尝试类似

key={ this.state.key + this.state.style.fillColor }

还要为不透明度分配fillOpacity: this.props.color,

这样的颜色,这很奇怪

那不是0到1之间的数字吗?