簡體   English   中英

組件之間共享狀態

[英]Sharing State Between Components

我要制作兩個組件:App和Map。 但是,當我嘗試制作新的品牌Map組件並將數據從App發送到Map組件時,我無法。

我的應用程序(默認)組件將數據保存為狀態。 當我嘗試將此狀態發送到Map組件時。 它以數據為支撐。

當然,如果我不分離它們並在App.js中編寫所有內容,那么一切都會按我的預期工作(地圖上顯示的標記)。 但是我想控制父組件中的所有狀態。

我違反基本的React規則嗎? 我該如何解決?

App.js

import React, { Component } from "react";
import "./App.css";
import Map from "./Map";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      locations: [],
      markers: []
    };
  }

  componentDidMount() {
    fetch(
      "correct_foursquare_api_url"
    )
      .then(response => response.json())
      .then(data =>
        data.response.venues.map(place => ({
          id: place.id,
          name: place.name,
          lat: place.location.lat,
          lng: place.location.lng
        }))
      )
      .then(locations => {
        this.setState({ locations });
      });
  }

  render() {
    return (
      <div className="App">
      <Map locations={this.state.locations} />
      </div>
      )
  }
}

export default App;

Map.js

import React, { Component } from "react";
/* global google */

class Map extends Component {
  constructor(props) {
    super(props);
    this.state = {
      locations: [],
      markers: []
    };
  }

  componentDidMount() {
    this.callMap();
  }

  callMap() {
    window.initMap = this.initMap;
    loadJS(
      "api_url"
    );
  }

  // Map
  initMap = () => {
    const { locations, markers } = this.state;
    let map = new google.maps.Map(document.getElementById("map"), {
      center: { lat: 59.4827293, lng: -83.1405355 },
      zoom: 13
    });

    // Markers
    for (var i = 0; i < locations.length; i++) {
      var title = locations[i].name;
      var position = new google.maps.LatLng(locations[i].lat, locations[i].lng);
      var id = locations[i].id;
      var marker = new google.maps.Marker({
        map: map,
        position: position,
        title: title,
        animation: google.maps.Animation.DROP,
        id: id
      });
      markers.push(marker);
    }
  };

  render() {
    return <div id="map" />;
  }
}

function loadJS(src) {
  var ref = window.document.getElementsByTagName("script")[0];
  var script = window.document.createElement("script");
  script.src = src;
  script.async = true;
  ref.parentNode.insertBefore(script, ref);
}

export default Map;

您將locations存儲在App組件的狀態下,但是在安裝時也使用了處於Map組件狀態的locations

相反,您可以等待渲染Map組件,直到完成locations請求,然后使用從App傳遞來的Map組件中的locations道具。

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      locations: [],
      markers: []
    };
  }

  componentDidMount() {
    fetch("correct_foursquare_api_url")
      .then(response => response.json())
      .then(data => {
        const locations = data.response.venues.map(place => ({
          id: place.id,
          name: place.name,
          lat: place.location.lat,
          lng: place.location.lng
        }));

        this.setState({ locations });
      });
  }

  render() {
    const { locations, markers } = this.state;

    if (locations.length === 0) {
      return null;
    }

    return (
      <div className="App">
        <Map locations={locations} markers={markers} />
      </div>
    );
  }
}

class Map extends Component {
  // ...

  initMap = () => {
    const { locations, markers } = this.props;

    // ...
  };

  // ...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM