组件之间共享状态

时间:2018-08-06 00:32:40

标签: javascript reactjs

我想制作两个组件: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;

1 个答案:

答案 0 :(得分:0)

您将locations的状态存储在App组件的状态,但是您也将locations的状态存储在挂载时使用的Map的状态。

您可以改为渲染Map组件,直到完成locations请求,然后使用locations传递的Map组件中的App道具1}}。

示例

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;

    // ...
  };

  // ...
}