ReactJS 生命周期方法不能按顺序工作

ReactJS lifecycle methods not working in sequence

我正在研究 Google ReactJS 中的地图渲染。为此,我正在使用 '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.

在状态本身中调用 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>

你应该像那样检查数据是否存在然后只给出值。

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

切勿在 componentWillMount() 中执行提取操作,而是使用 componentDidMount(),因为调用 setState() 会重新渲染组件,您可能会在地图上看到新数据。