ReactJS谷歌地图组件不会重新渲染

瓦伦丁·巴尔塔基耶夫(Valentin Baltadzhiev)

我正在编写一个Web应用程序,该应用程序允许您输入地址并使用从给定地址到其他4个地址(目前为硬编码)的方向来呈现地图。一切正常,直到我想输入新地址并刷新地图

我正在使用tomchentw / react-google-maps库获取路线并渲染地图

这是我的代码:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import { compose, withProps, withPropsOnChange, withState, lifecycle } from     "recompose";
import {
withScriptjs,
withGoogleMap,
GoogleMap,
Marker,
DirectionsRenderer,
} from "react-google-maps";

const MapWithADirectionsRenderer = compose(
withProps({
    googleMapURL: "https://maps.googleapis.com/maps/api/js?key=AIzaSyC4R6AN7SmujjPUIGKdyao2Kqitzr1kiRg&v=3.exp&libraries=geometry,drawing,places",
    loadingElement: <div style={{ height: `100%` }} />,
    containerElement: <div style={{ height: `500px` }} />,
    mapElement: <div style={{ height: `100%` }} />,
}),        
withScriptjs,
withGoogleMap,
lifecycle({
    componentDidMount() {
        this.setState({
            newDirections: [],
        });

        let destinations = ['Imperial College', '123 Aldersgate Street', '17 Moorgate', 'Spitafields Market']

        const DirectionsService = new google.maps.DirectionsService();

        DirectionsService.route({
            origin: this.props.origin,
            destination: destinations[0],
            travelMode: google.maps.TravelMode.TRANSIT,
        }, (result, status) => {
            if (status === google.maps.DirectionsStatus.OK) {
                this.setState({
                    directions: result,
                    newDirections: this.state.newDirections.concat([result])
                });
            } else {
                console.error(`error fetching directions ${result}`);
            }
        });

        DirectionsService.route({
            origin: this.props.origin,
            destination: destinations[1],
            travelMode: google.maps.TravelMode.TRANSIT,
        }, (result, status) => {
            if (status === google.maps.DirectionsStatus.OK) {
                this.setState({
                    directions1: result,
                    newDirections: this.state.newDirections.concat([result])
                });
            } else {
                console.error(`error fetching directions ${result}`);
            }
        });

        DirectionsService.route({
            origin: this.props.origin,
            destination: destinations[2],
            travelMode: google.maps.TravelMode.TRANSIT,
        }, (result, status) => {
            if (status === google.maps.DirectionsStatus.OK) {
                this.setState({
                    directions2: result,
                    newDirections: this.state.newDirections.concat([result])
                });
            } else {
                console.error(`error fetching directions ${result}`);
            }
        });

        DirectionsService.route({
            origin: this.props.origin,
            destination: destinations[3],
            travelMode: google.maps.TravelMode.TRANSIT,
        }, (result, status) => {
            if (status === google.maps.DirectionsStatus.OK) {
                this.setState({
                    directions3: result,
                    newDirections: this.state.newDirections.concat([result])
                });
            } else {
                console.error(`error fetching directions ${result}`);
            }
        });
    }      
})
)(props =>
<GoogleMap
    defaultZoom={7}
    defaultCenter={new google.maps.LatLng(51.435341, -0.131116)}
>
    {props.directions && <DirectionsRenderer directions={props.newDirections[0]} />}
    {props.directions1 && <DirectionsRenderer directions={props.newDirections[1]} />}
    {props.directions2 && <DirectionsRenderer directions={props.newDirections[2]} />}
    {props.directions3 && <DirectionsRenderer directions={props.newDirections[3]} />}

</GoogleMap>
);

class AddressForm extends React.Component {
constructor(props) {
    super(props);
    this.state = { value: '' };

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
}

handleChange(event) {
    this.setState({ value: event.target.value });
}

handleSubmit(event) {

    let targetAddress = this.state.value;
    ReactDOM.render(<MapWithADirectionsRenderer origin={targetAddress} destination='Imperial College' />, document.getElementById('mapplace'));
    event.preventDefault();

}

render() {
    return (
        <form onSubmit={this.handleSubmit}>
            <label>
                Address:
                <input type="text" value={this.state.value} onChange={this.handleChange} />
            </label>
            <input type="submit" value="submit" />
        </form>
    );
}
}

registerServiceWorker();


ReactDOM.render(<AddressForm />, document.getElementById('formplace'));

加载后,用户只能看到已渲染的组件。输入地址并提交表单后,地图将正确显示。但是,当我输入新地址并重新提交表单时,地图不会重新显示。

我有什么想念的吗?

瓦迪姆·格雷米亚切夫(Vadim Gremyachev)

您可能正在寻找componentDidUpdate在任何更新发生后运行的函数该函数componentDidMount在第一次渲染后只会被调用一次。

我将提出以下更改列表:

a)引入一个单独的功能来绘制路线:

 drawRoutes() {
        let destinations = ['Imperial College', '123 Aldersgate Street', '17 Moorgate', 'Spitafields Market']
        const DirectionsService = new google.maps.DirectionsService();
        DirectionsService.route({
            origin: this.props.origin,
            destination: destinations[0],
            travelMode: google.maps.TravelMode.TRANSIT,
        }, (result, status) => {
            if (status === google.maps.DirectionsStatus.OK) {
                this.setState({
                    directions: result,
                    newDirections: this.state.newDirections.concat([result])
                });
            } else {
                console.error(`error fetching directions ${result}`);
            }
        });

        DirectionsService.route({
            origin: this.props.origin,
            destination: destinations[1],
            travelMode: google.maps.TravelMode.TRANSIT,
        }, (result, status) => {
            if (status === google.maps.DirectionsStatus.OK) {
                this.setState({
                    directions1: result,
                    newDirections: this.state.newDirections.concat([result])
                });
            } else {
                console.error(`error fetching directions ${result}`);
            }
        });

        DirectionsService.route({
            origin: this.props.origin,
            destination: destinations[2],
            travelMode: google.maps.TravelMode.TRANSIT,
        }, (result, status) => {
            if (status === google.maps.DirectionsStatus.OK) {
                this.setState({
                    directions2: result,
                    newDirections: this.state.newDirections.concat([result])
                });
            } else {
                console.error(`error fetching directions ${result}`);
            }
        });

        DirectionsService.route({
            origin: this.props.origin,
            destination: destinations[3],
            travelMode: google.maps.TravelMode.TRANSIT,
        }, (result, status) => {
            if (status === google.maps.DirectionsStatus.OK) {
                this.setState({
                    directions3: result,
                    newDirections: this.state.newDirections.concat([result])
                });
            } else {
                console.error(`error fetching directions ${result}`);
            }
        });
    }

b)设置初始状态:

  componentWillMount() {
       this.setState({
                newDirections: [],
       });
   }

c)绘制路线:

componentDidMount() {
        this.drawRoutes();
}

d)如果地址已更改,则重画路线

componentDidUpdate(prevProps, prevState) {
     if (prevProps.origin !== this.props.origin) {
          this.setState({
              directions: null,
              directions1: null,
              directions2: null,
              directions3: null,
              newDirections: []
         });
         this.drawRoutes();
     }
}

演示版

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

reactjs-更改状态不会重新渲染组件

reactjs useState:选择 onChange 触发 setState 但组件不会重新渲染

componentWillReceiveProps不会重新渲染组件

React - Google Map 组件在重新渲染后不会更改地图

React 组件的地图不会在状态变化时重新渲染

上下文值更改后,标题导航中的 ReactJS 组件不会再次重新渲染

ReactJS-内联样式不会在重新渲染组件时更新

Mobx不会重新渲染React组件

反应:setState不会重新渲染组件

setState 后组件不会重新渲染

子组件不会被重新渲染

React/Redux 组件不会重新渲染

状态变化不会重新渲染组件

ReactJs:防止包装组件的重新渲染

在 this.setState() 之后 Reactjs 不会重新渲染

谷歌地图的渲染问题

emberjs组件不会重新渲染组件以更新fullcalendar

重新渲染组件不会更新功能组件内的对象

POST请求后,子组件不会重新渲染父组件

谷歌地图 Infowindow ReactJS

使用 Redux 和 React Hooks,Flatlist 不会重新渲染,也不会重新渲染其中的各个组件

使用eletegerjs渲染谷歌地图

为什么 mobX 操作不会触发 React 组件的重新渲染

React 16.13.1 - 当 props 改变时子组件不会重新渲染

当 props 改变时,React 组件不会重新渲染

当道具更改时,React 子组件不会重新渲染

即使状态已更新,组件也不会重新渲染

useState不会更新组件重新渲染时的值

在 mobx 中更新状态时组件不会重新渲染