繁体   English   中英

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

[英]React component (GeoJSON) not re-rendering on state change

我使用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] }
                        />
                    )
                ))
            }

使用滑块更改颜色和组件的功能效果很好,因此我看不到需要在此处添加它们的功能。 感谢您为我们提供的解决方案!

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

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

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

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

同样奇怪的是,您为不透明度分配了诸如fillOpacity: this.props.color,这样的颜色fillOpacity: this.props.color,

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM