【问题标题】:ReactJS lifecycle methods not working in sequenceReactJS 生命周期方法不按顺序工作
【发布时间】:2019-03-23 06:55:54
【问题描述】:

我正在使用 ReactJS 进行 Google 地图渲染。为此,我正在使用“react-google-maps”库。逻辑流程是;在页面加载时,获取用户的位置并将其绘制在地图上。 为用户提供导航链接以点击不同的 URL。为了处理导航,我使用了 React 路由器。用户的位置在 componentWillMount() 中标识,然后相应地设置状态并在 render() 中渲染地图。 问题是 render() 在完成 componentWillMount() 之前被调用,它获取空值并且失败。这种情况只发生在客户端路由中,不会出现在服务器端渲染中。

为了限制执行方式,我将 componentWillMount() 设置为异步方法,它会一直等待直到确定用户的位置。尽管如此,它还是没有帮助。

state = {
        homeLocation: {},
        coordinates: []
    }

async componentWillMount(props) {
        const { lat,lng } = await this.getcurrentLocation();
        this.setState({
            homeLocation:{
                lat: lat, 
                lng: lng
            }
        })
    }

getcurrentLocation() {

        if (window.navigator && window.navigator.geolocation) {
          return new Promise((resolve, reject) => {
            window.navigator.geolocation.getCurrentPosition(pos => {
              const coords = pos.coords;
              resolve({
                lat: coords.latitude,
                lng: coords.longitude
              });
            });
          });
        }
        return {
          lat: 0,
          lng: 0
        };
      }
render(){

   <MapWithAMarker
   // necessary parameters
  />
}

//Routers
const AppRouter = () => (
    <Router>
        <div>
            <Switch>
                <Route path="/" component={MapHomeLocation} exact={true}/>
                <Route path="/location/:locationType" component={MapSelectedLocation}/>
                <Route component={Notfound}/>
            </Switch>
        </div>

    </Router>
);


The expected result is that coordinates should be determined first then render() should get called. In server-side routing(i.e. using anchor tags instead of <Link>) it works as expected.

【问题讨论】:

    标签: javascript reactjs react-router react-google-maps


    【解决方案1】:

    你应该这样检查是否有数据,然后只给出价值。

    如果数据 && data.length > 0 ?数据:空

    【讨论】:

    • 你能解释一下我可以把这个条件放在哪里吗?我是 ReactJS 概念的新手。您的评论会有所帮助。
    • 因为当您为 api 获取一些数据时,第一次获取 null,因此我们需要检查并将条件放入其中,如果数据为空,则不分配,如果数据不为空,则分配@Swapnil
    • 在componentwilmount方法中移除async和await
    • 把getcurrentLocation()放到组件里面会挂载
    • 如果您需要更多帮助,我们可以在任何办公桌上联系,我会帮助您。
    【解决方案2】:

    在状态本身中调用 getcurrentLocation()。

    state = {
            homeLocation: this.getcurrentLocation(),
            coordinates: []
        }
    
    
    
    getcurrentLocation() {
    
            if (window.navigator && window.navigator.geolocation) {
              return new Promise((resolve, reject) => {
                window.navigator.geolocation.getCurrentPosition(pos => {
                  const coords = pos.coords;
                  resolve({
                    lat: coords.latitude,
                    lng: coords.longitude
                  });
                });
              });
            }
            return {
              lat: 0,
              lng: 0
            };
          }
    render(){
    
       <MapWithAMarker
       // necessary parameters
      />
    }
    
    //Routers
    const AppRouter = () => (
        <Router>
            <div>
                <Switch>
                    <Route path="/" component={MapHomeLocation} exact={true}/>
                    <Route path="/location/:locationType" component={MapSelectedLocation}/>
                    <Route component={Notfound}/>
                </Switch>
            </div>
    
        </Router>
    );
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

    【讨论】:

    • 如果您不介意让代码 sn-p 设置状态值。由于 getcurrentLocation() 返回两个值,如何将它们分配给 state 中的 homeLocation 对象。
    【解决方案3】:

    永远不要在componentWillMount() 中进行获取操作,而是使用componentDidMount(),因为调用setState() 会重新渲染组件,您可能会在地图上看到新数据。

    【讨论】:

    • 什么行为?
    • 在渲染方法中获取空坐标。使用 componentWillMount(),它有时会获取坐标。
    猜你喜欢
    • 1970-01-01
    • 2020-05-02
    • 1970-01-01
    • 2020-07-20
    • 1970-01-01
    • 1970-01-01
    • 2018-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多