React Redux - 子组件不会在状态更改时重新呈现

时间:2017-12-21 14:45:02

标签: javascript reactjs redux react-redux

架构是这样的:我有一个plotMap组件,它从状态中获取一个图表列表,并将它们映射到一堆plotMarker组件,这些组件根据地图返回多边形/标记缩放(也从状态读取)。如果选择给定的绘图进行编辑,则plotMarker组件将返回可编辑的plotPolygon组件。当用户保存已编辑的plotPolygon组件时,这将更新状态图列表中的相应图。

问题:成功保存已编辑的plotMarker组件后立即显示的plotPolygon多边形不会使用新形状更新,而是保留旧形状。只有当一个缩小,并且plotMarker渲染其标记组件并重新放大,并且plotMarker再次渲染其多边形组件时,才会显示新的形状。

这可能是由于应用程序内部滞后造成的吗?如何在plotMarker成功保存后立即显示新多边形?

plotMap组件

import React, { Component } from 'react';
import { connect } from 'react-redux';
import * as actions from '../../actions';
import { Map, TileLayer, LayersControl, MapControl } from 'react-leaflet';
import { GoogleLayer } from './GoogleLayer';
import { geolocated } from 'react-geolocated';
import 'leaflet-geocoder-mapzen';
import SearchBox from './searchBox';
import Control from 'react-leaflet-control';
import { centroid } from '@turf/turf';
import PlotMarker from './plotMarker';

const { BaseLayer } = LayersControl;
const key = 'key';
const hybrid = 'HYBRID';
const terrain = 'TERRAIN';
const road = 'ROADMAP';
const satellite = 'SATELLITE';

const centerLat = props => {
    if (
        props.isGeolocationAvailable &&
        props.isGeolocationEnabled &&
        props.coords
    ) {
        return props.coords.latitude;
    }
    return 32.11;
};

const centerLong = props => {
    if (
        props.isGeolocationAvailable &&
        props.isGeolocationEnabled &&
        props.coords
    ) {
        return props.coords.longitude;
    }
    return 34.963;
};

const mapCenterPoint = props => {
    if (props.plots && (props.selectedPlot || props.plotBeingEdited)) {
        let ourPlot = props.plots.filter(
            plot => plot._id === (props.selectedPlot || props.plotBeingEdited)
        )[0];
        try {
            let center = centroid(ourPlot.feature).geometry.coordinates.reverse();
            return { center: center, zoom: 16 };
        } catch (e) {
            console.log(e);
        }
    }
    return { center: [centerLat(props), centerLong(props)], zoom: 8 };
};

export class PlotMap extends Component {
    markers = props => {
        if (props.plots) {
            return (
                <div>
                    {(props.filteredPlots || props.plots).map(
                        plot =>
                            plot &&
                            plot.feature &&
                            plot._id && (
                                <PlotMarker
                                    key={plot._id}
                                    id={plot._id}
                                    name={plot.name}
                                    geoJSON={plot.feature}
                                />
                            )
                    )}
                </div>
            );
        }
    };

    render() {
        return (
            <div
                className="col-sm-8 m-auto p-0 flex-column float-right"
                style={{ height: `85vh` }}>
                <Map
                    center={mapCenterPoint(this.props).center}
                    zoom={mapCenterPoint(this.props).zoom}
                    zoomControl={true}
                    onZoomend={e => {
                        this.props.setZoomLevel(e.target.getZoom());
                    }}
                    onMoveEnd={e => {
                        this.props.setMapCenter(e.target.getCenter());
                    }}>
                    <LayersControl position="topright">
                        <BaseLayer name="Google Maps Roads">
                            <GoogleLayer googlekey={key} maptype={road} />
                        </BaseLayer>
                        <BaseLayer name="Google Maps Terrain">
                            <GoogleLayer googlekey={key} maptype={terrain} />
                        </BaseLayer>
                        <BaseLayer checked name="Google Maps Hybrid">
                            <GoogleLayer
                                googlekey={key}
                                maptype={hybrid}
                                libraries={['geometry', 'places']}
                            />
                        </BaseLayer>
                    </LayersControl>
                    <SearchBox postion="bottomright" />
                    {this.markers(this.props)}
                </Map>
            </div>
        );
    }
}

function mapStateToProps(state) {
    return {
        filteredPlots: state.plots.filteredPlots,
        plots: state.plots.plots,
        selectedPlot: state.plots.selectedPlot,
        mapCenter: state.plots.mapCenter
    };
}

export default geolocated({
    positionOptions: {
        enableHighAccuracy: false
    },
    userDecisionTimeout: 5000,
    suppressLocationOnMount: false
})(connect(mapStateToProps, actions)(PlotMap));

plotMarker组件:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import * as actions from '../../actions';
import { Marker, Popup, GeoJSON } from 'react-leaflet';
import { centroid } from '@turf/turf';
import PlotPolygon from './plotPolygon';

const position = geoJSON => {
    return centroid(geoJSON).geometry.coordinates.reverse();
};

export class PlotMarker extends Component {
    render() {
        const {
            id,
            name,
            geoJSON,
            zoomLevel,
            selectedPlot,
            plotBeingEdited
        } = this.props;
        const markerPosition = position(geoJSON);
        let style = () => {
            return {
                color: 'blue'
            };
        };
        if (selectedPlot === id) {
            style = () => {
                return {
                    color: 'red'
                };
            };
        }
        if (zoomLevel > 14 && plotBeingEdited === id) {
            return <PlotPolygon id={id} geoJSON={geoJSON} />;
        } else if (zoomLevel > 14) {
            return (
                <GeoJSON
                    id={id}
                    data={geoJSON}
                    style={style}
                    onClick={() => {
                        this.props.selectPlot(id);
                    }}
                />
            );
        }
        return (
            <Marker
                id={id}
                className="marker"
                position={markerPosition}
                onClick={() => {
                    this.props.selectPlot(id);
                }}>
                <Popup>
                    <span>{name}</span>
                </Popup>
            </Marker>
        );
    }
}

function mapStateToProps(state) {
    return {
        selectedPlot: state.plots.selectedPlot,
        plotBeingEdited: state.plots.plotBeingEdited,
        zoomLevel: state.plots.zoomLevel,
        plots: state.plots.plots,
        filteredPlots: state.plots.filteredPlots
    };
}

export default connect(mapStateToProps, actions)(PlotMarker);

plotPolygon组件

import React, { Component } from 'react';
import { connect } from 'react-redux';
import * as actions from '../../actions';
import { Polygon, FeatureGroup } from 'react-leaflet';
import { EditControl } from 'react-leaflet-draw';

const positions = props => {
    return props.geoJSON.geometry.coordinates[0].map(a => [a[1], a[0]]);
};

export class PlotPolygon extends Component {
    render() {
        const { id, geoJSON } = this.props;
        return (
            <FeatureGroup>
                <EditControl
                    position="topright"
                    onEdited={e => {
                        e.layers.eachLayer(a => {
                            this.props.updatePlot({
                                id: id,
                                feature: a.toGeoJSON()
                            });
                        });
                    }}
                    edit={{ remove: false }}
                    draw={{
                        marker: false,
                        circle: false,
                        rectangle: false,
                        polygon: false,
                        polyline: false
                    }}
                />
                <Polygon positions={[positions(this.props)]} />;
            </FeatureGroup>
        );
    }
}

function mapStateToProps(state) {
    return { plots: state.plots.plots, filteredPlots: state.plots.filteredPlots };
}

export default connect(mapStateToProps, actions)(PlotPolygon);

1 个答案:

答案 0 :(得分:2)

原始解决方案:

退出编辑模式后,是否需要重置缩放级别?您的逻辑与mapCenterPointif(zoomLevel...的{​​{1}}部分紧密耦合。我想知道你是否有一个状态导致它在编辑后总是评估为真(直到手动缩放):plotMarker

关于重构的想法:

  

找出更优雅的方式

选项1:HOC

高阶组件(或HOC)可能是一个很好的方法。您的代码中已经有一个HOC示例:

props.plots && (props.selectedPlot || props.plotBeingEdited)

HOC实际上只是在React世界中返回对你有用的东西的函数。因此,它们是一种很好的代码重用形式。 export default connect(mapStateToProps, actions)(PlotMarker); 是在此场景中返回函数的HOC,但HOC通常用于返回组件。因此,您可能有一个像connect这样的HOC执行逻辑本身来确定要呈现的标记组件类型。

查看React's Higher Order Component Documentation了解更多信息。

选项2:单一退货声明

我一直都喜欢为render方法使用单个return语句。我还没有深入挖掘React如何处理差异,但我很确定从我的经验来看,这种方式反应更好 - 所以它可能无需你抽搐缩放级别来重置它。

我如何在一个回复中执行plotMarker(zoomLevel, beingEdited)的所有逻辑:

PlotMarker