在组件之间共享状态

问题描述 投票:2回答:1

我想制作两个组件: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;
javascript reactjs
1个回答
0
投票

你将locations存储在App组件的状态中,但你也有locations处于你在mount上使用的Map组件的状态。

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

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;

    // ...
  };

  // ...
}
© www.soinside.com 2019 - 2024. All rights reserved.