我在做一个使用react-google-maps包的项目的过程中正在自学React,以生成从A到B的方向的 map 。该 map 本身工作正常,但是我现在尝试通过return方法在html中打印相应的路线方向但无法获取这些说明以进行打印。

通过Google和StackOverflow的研究,我认为我的问题可能是:

  • 尝试在return方法中访问我的instructionList时,“this”关键字的范围。在哪种情况下-我需要输入什么才能访问instructionList项的<li>数组?
    我也尝试过<ol>{DirectionsService.route.state.instructionList}</ol><ol> and {DirectionsComponent.DirectionsService.route.state.instructionList}</ol>也不起作用
  • 加载页面时,不一定收到api响应,因此我的instructionList为null,无法呈现。在哪种情况下-应该如何处理?
  • 语法中我还没有意识到的其他东西(我是一个非常新手,它是React和Google-maps软件包!)

  • 在我的代码中,我在状态中定义了一个名为指令列表的数组,其中包含从A到B的指令
    if (status === google.maps.DirectionsStatus.OK) {
      this.setState({
        directions: { ...result },
        markers: true
      });
      this.setState({
        instructions: this.state.directions.routes[0].legs[0].steps
      });
      this.setState({
        instructionList: this.state.instructions.map(instruction => {
          return <li>instruction.instructions</li>;
        })
      });
    }
    

    然后,我尝试在类返回方法中访问此数组-但错误消息是未定义instructionList
    return (
      <div>
          <DirectionsComponent/>
          <div className="route instructions">
            <h1>{title}</h1>
            <ol>{this.state.instructionList}</ol>
          </div>
          <NotificationContainer />
      </div>
    

    如果能更轻松地确定问题,则下面是一段完整的代码。
    class MyMapComponent extends React.Component {
      constructor(props) {
        super(props);
      }
      render() {
        const {
          startLat,
          startLng,
          finishLat,
          finishLng,
          transportMode,
          title
        } = this.props;
    
        const DirectionsComponent = compose(
          withProps({
            googleMapURL:
              "https://maps.googleapis.com/maps/api/js?key=APIKEYGOESHERE", //removed=&callback=initMap
            loadingElement: <div style={{ height: `400px` }} />,
            containerElement: <div style={{ width: `100%` }} />,
            mapElement: <div style={{ height: `400px`, width: `400px` }} />
          }),
          withScriptjs,
          withGoogleMap,
          lifecycle({
            componentDidMount() {
              const DirectionsService = new google.maps.DirectionsService();
    
              DirectionsService.route(
                {
                  origin: new google.maps.LatLng(startLat, startLng),
                  destination: new google.maps.LatLng(finishLat, finishLng),
                  travelMode: google.maps.TravelMode[transportMode],
                  provideRouteAlternatives: true
                },
                (result, status) => {
                  if (status === google.maps.DirectionsStatus.OK) {
                    this.setState({
                      directions: { ...result },
                      markers: true
                    });
                    this.setState({
                      instructions: this.state.directions.routes[0].legs[0].steps
                    });
                    this.setState({
                      instructionList: this.state.instructions.map(instruction => {
                        return <li>instruction.instructions</li>;
                      })
                    });
                  } else {
                    console.error(
                      `There was an error fetching directions for the specified journey ${result}`
                    );
                    NotificationManager.error(
                      "Journey cannot be retrieved, please try again",
                      "Error",
                      20000
                    );
                  }
                }
              );
            }
          })
        )(props => (
          <GoogleMap defaultZoom={3}>
            {props.directions && (
              <DirectionsRenderer
                directions={props.directions}
                suppressMarkers={props.markers}
              />
            )}
          </GoogleMap>
        ));
        return (
          <div>
            <DirectionsComponent />
            <div className="route instructions">
              <h1>{title}</h1>
              <ol>{this.state.instructionList}</ol>
            </div>
            <NotificationContainer />
          </div>
        );
      }
    }
    export default MyMapComponent;
    

    错误消息当前为TypeError: Cannot read property 'instructionList' of null
    我玩过代码并进行了很多研究,但我会绕圈转。我确定该解决方案是一种快速的解决方案,但由于我对React / react-google-maps的了解有限,因此我一直在努力寻找解决方案,因此,我非常感谢能够提供帮助的任何人:)

    最佳答案

    您尚未初始化组件的state。因此,您无法访问state的属性。您需要使用constructor对其进行初始化。

     constructor(props){
        super(props);
        this.state = { instructionList: [] };
      }
    

    更新

    您需要定义onChangeInstructionList才能在MyMapComponent中更改instructionListDirectionsComponent。您还需要将DirectionsComponent移到componentDidMountMyMapComponent,以避免由于状态更改而导致无限循环。
    class MyMapComponent {
      constructor(props){
        super(props);
        this.state = {
          instructionList: [],
        };
    
        this.onChangeInstructionList = this.onChangeInstructionList.bind(this);
      }
    
      componentDidMount() {
        const {startLat, startLng, finishLat, finishLng, transportMode} = this.props;
        const DirectionsComponent = compose(
          withProps({
            googleMapURL: "https://maps.googleapis.com/maps/api/js?key=APIKEYGOESHERE",//removed=&callback=initMap
            loadingElement: <div style={{ height: `400px` }} />,
            containerElement: <div style={{ width: `100%` }} />,
            mapElement: <div style={{height: `400px`, width: `400px` }}  />,
            onChangeInstructionList: this.onChangeInstructionList,
          }),
          withScriptjs,
          withGoogleMap,
          lifecycle({
            componentDidMount() {
              const DirectionsService = new google.maps.DirectionsService();
    
              DirectionsService.route({
                origin: new google.maps.LatLng(startLat, startLng),
                destination: new google.maps.LatLng(finishLat, finishLng),
                travelMode: google.maps.TravelMode[transportMode],
                provideRouteAlternatives: true
              }, (result, status) => {
    
                if (status === google.maps.DirectionsStatus.OK) {
                  this.setState({
                    directions: {...result},
                    markers: true
                  })
                  this.setState({instructions: this.state.directions.routes[0].legs[0].steps});
                  this.props.onChangeInstructionList(this.state.instructions.map(instruction => {
                    return (<li>instruction.instructions</li>);
                  }));
                } else {
                  console.error(`There was an error fetching directions for the specified journey ${result}`);
                  NotificationManager.error("Journey cannot be retrieved, please try again", "Error", 20000);
                }
              });
            }
          })
        )(props =>
          <GoogleMap
            defaultZoom={3}
          >
            {props.directions && <DirectionsRenderer directions={props.directions} suppressMarkers={props.markers}/>}
          </GoogleMap>
        );
    
        this.setState({
          DirectionsComponent,
        })
      }
    
      onChangeInstructionList(newList) {
        this.setState({
          instructionList: newList,
        });
      }
    
      render() {
        const {title} = this.props;
        const { DirectionsComponent, instructionList } = this.state;
        return (
          <div>
            <DirectionsComponent/>
            <div className="route instructions">
              <h1>{title}</h1>
              <ol>{instructionList}</ol>
            </div>
            <NotificationContainer />
          </div>
    
        )
      }
    }
    export default MyMapComponent
    

    关于javascript - 无法通过渲染返回调用访问状态- 'Cannot read property '指令列表为null',我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57342959/

    10-12 07:01