无法停止在Reactjs中渲染组件

时间:2018-07-09 07:55:39

标签: javascript reactjs redux react-redux redux-thunk

在我的reactjs应用中,我正在使用 Redux Redux-Thunk 。在使用google-maps的组件中,我想实现{{1} }使用Markers.so,每当我移动标记 latlng 地址时也会更改。当我正在保存状态组件时要刷新。因此,我想停止使用center_changed渲染组件。但是当我从shouldComponentUpdate返回false时,地图也会刷新。
我的组件

shouldComponentUpdate

ActionCreator

class StepTwo extends React.Component{
    constructor(props){
        super(props);
        this.state={
            pickupConfirmButton:false,
            dropoffConfirmButton:false,
        }
        this.mapLoaded = false;
        this.map=false;
        this.pickMarker=false;
        this.pickIcon = '';
        this.dropMarker=false;
        this.dropIcon='';
    }
    componentWillReceiveProps(props){
        if (props.isScriptLoadSucceed) {
            this.mapLoaded= true;
            this.directionsService = new google.maps.DirectionsService();
            this.directionsDisplay = new google.maps.DirectionsRenderer({ suppressMarkers: true });

            this.map = new google.maps.Map(document.getElementById('map'), {
                zoom: 14,
                center: { lat: 17.3850, lng: 78.4867 },
                mapTypeControl: false,
                streetViewControl: false,
                gestureHandling:'greedy',
            });

            this.pickMarker = new google.maps.Marker   ({
                icon:this.pickIcon,
                map: this.map,
                animation: google.maps.Animation.DROP,
                position: { lat: 17.3850, lng: 78.4867 },
                // draggable: true
            });
            this.dropIcon = {
                path: 'M 0,0 C -2,-20 -10,-22 -10,-30 A 10,10 0 1,1 10,-30 C 10,-22 2,-20 0,0 z M -2,-30 a 2,2 0 1,1 4,0 2,2 0 1,1 -4,0',
                fillColor: '#00E64D',
                fillOpacity: 1,
                strokeColor: '#000',
                strokeWeight: 1,
                scale: 1,
            };

            this.pickMarker.addListener('click', () =>{
                this.pickupMarkerClickListener();
            });
        }
    }
    shouldComponentUpdate(nextProps, nextState) {
        if (this.props.pickupAddress || nextProps.pickupAddress) {
           //after return false also i'm unable to stop rendering 
           //component
            return false;
        }
    }

    pickupMarkerClickListener = () =>{
        if(this.dropMarker){
            this.dropMarker.setVisible(false);
        }
        this.directionsDisplay.set('directions', null);
        this.map.setCenter(this.pickMarker.getPosition());
        this.map.setZoom(18);

        this.map.addListener('center_changed',  () => {
            let lat=this.map.getCenter().lat();
            let lng=this.map.getCenter().lng();
            let pickLatlng ={lat:lat,lng:lng};
            //on below function when i want to send latlng to redux state component getting refresh.
            // this.props.pickupHandler(pickLatlng);
            let geocoder = new google.maps.Geocoder;
                geocoder.geocode({'location': {lat:lat,lng:lng}}, (results, status) =>{
                    if (status === 'OK') {
                        ////////////////////////////////////////////////////////
                        //////// this is function which getting refresh/////////
                        ///////////////////////////////////////////////////////
                        this.props.pickupAddHandler(results[0].formatted_address);
                    }
                })
            this.pickMarker.setPosition({lat:lat,lng:lng});
        })
    }
    render(){
        return(
            <Row type="flex" justify="space-around" align="middle" className='stepTwo'>
                <Col lg={{span:10}} className="form" >
                    <Input 
                            className='input'
                            placeholder='Enter Pick-up Locaiton'
                            id='pick'
                            ref="pickupInput"
                            onChange={this.pickupSearch}
                            // value={this.props.pickupAddress}
                        />
                    <div style={{padding:'1rem'}} align='center'>
                    <Button><Icon type="swap"  className="swapIcon" /> </Button><span style={{fontSize:'0.8rem'}}>*Reverse Location</span>
                    </div>
                    <Input 
                        className='input'
                        placeholder='Enter Drop-off Locaiton'
                        ref="dropoffInput"
                        onChange={this.dropoffSearch}

                    />
                </Col>
                <Col lg={{span:13}}>
                    <div id="map"  className='map'></div>
                    {this.state.pickupConfirmButton && <Button  className="cnfrmBtn"  size="large" onClick={this.pickupMaker}>Confirm Location</Button> }
                    {this.state.dropoffConfirmButton && <Button className="cnfrmBtn" size="large" onClick={this.dropoffMaker}>Confirm Location</Button> }
                </Col>
            </Row>
        )
    }
}

const StepTwoLoadedMap = scriptLoader(
    [config.MapApi]
)(StepTwo);

const mapStateToProps = (state) =>{
    console.log(state.StepTwoReducer.pickupLatlng,'mapState')
    return{
        pickupAddress:state.StepTwoReducer.pickupAddress,
        pickupLocation:state.StepTwoReducer.pickupLatlng
    }
}
export default connect(mapStateToProps,{validationS2,pickupAddHandler,pickupHandler,dropoffHandler})(StepTwoLoadedMap);

Reducer.js

export function pickupAddHandler(address){
    return function(dispatch){
        dispatch({type:PICKUPADD,payload:address})
    }
}

export function pickupHandler(latlng) {

    return function(dispatch) {
        dispatch({ type: PICKUP_LATLNG,payload:latlng });
    };
}

如何在import {VALIDS2,PICKUPADD,PICKUP_LATLNG} from '../actions/types'; const INITIAL_STATE = { validStepTwo:false, pickupAddress:null, pickupLatlng:false, }; export default (state=INITIAL_STATE,action) => { // console.log(action,'step two') switch(action.type) { case PICKUPADD: return {...state,pickupAddress:action.payload} case PICKUP_LATLNG: return {...state,pickupLatlng:action.payload} case VALIDS2: return {...state,validStepTwo:action.payload}; default: return state; } } 时在redux状态下存储地址和latlng,而无需呈现组件。
另一个问题是,当我更改地图中心时,我将获得地址,如果我们停止渲染组件,则该地址将存储center_changed状态,如果有输入字段,那么我想将该地址显示为输入字段值,如果组件未重新渲染,那么如何在输入字段中显示当前地址。
一些我不想使用任何库的原因
任何人都可以帮助我如何在不渲染的情况下存储redux状态,但是它应该在输入字段或任何其他简单方法中显示更新后的值,因为我已经停留了1周!plzzzzzz

1 个答案:

答案 0 :(得分:0)

始终尝试为第三方库(在这种情况下为Google地图)创建容器组件,并且始终在shouldComponentUpdate生命周期方法中返回false。 提供使用上下文的示例代码。

(id_properties, date_availabilities and id_availabilities)

这可能不是对您的问题的完美答案,但肯定会改善代码的结构并有助于解决问题。 希望对您有帮助!