【问题标题】:DirectionsRenderer and DirectionsService @react-google-maps/api not getting rendered and also not throwing errorDirectionsRenderer 和 DirectionsService @react-google-maps/api 没有被渲染也没有抛出错误
【发布时间】:2021-09-03 11:00:01
【问题描述】:

我正在尝试使用 @react-google-maps/api 的方向服务。

我正在使用 reactjs,文档链接是 https://react-google-maps-api-docs.netlify.app/#directionsservice

 {response !== null && (
                <DirectionsRenderer
                  // required
                  options={{
                    directions: response
                  }}
                />
              )}

我做错了什么。我也没有。

【问题讨论】:

    标签: reactjs react-google-maps


    【解决方案1】:

    地图被渲染了很多次。根据文档,他们在渲染期间设置状态。渲染应该始终保持纯净。在渲染和其他一些反应生命周期钩子中做副作用的事情是一种非常糟糕的做法。

    我认为他们必须努力改进文档。如果我们按照文档进行操作,它会给出指导,但您会收到超出谷歌地图配额的错误。

     const [response, setResponse] = React.useState(null);
       const directionsCallback = res => {
           console.log('? => res', res);
        if (res !== null) {
          if (res.status === 'OK') {
            setResponse(res);
          } else {
            console.log('res: ', res);
          }
        }
      };
    
             <DirectionsService
                options={{
                  destination: destination,
                  origin: origin,
                  travelMode: 'DRIVING'
                }}
                callback={directionsCallback}
              />
    

    更新:

    这解决了多重渲染

    let count = React.useRef(0);
    
    const directionsCallback = React.useCallback(res => {
        console.log(count.current);
        if (res !== null) {
          if (res.status === 'OK' && count.current < 2) {
            count.current += 1;
            setResponse(res);
          } else {
            count.current = 0;
            console.log('res: ', res);
          }
        }
      }, []);
    

    【讨论】:

      猜你喜欢
      • 2017-08-02
      • 2023-04-01
      • 2022-09-29
      • 2011-04-23
      • 1970-01-01
      • 2018-07-03
      • 1970-01-01
      • 2017-04-15
      • 1970-01-01
      相关资源
      最近更新 更多