Маркер GoogleMap не обновляется при вводе поиска, хотя его свойства - PullRequest
0 голосов
/ 13 июля 2020

В Search есть вход. js, который выполняет обратный вызов в App. js и изменяет состояние newPlaces на массив, отфильтрованный поисковым запросом, по сравнению с массивом places.

This затем передается в Map. js с реквизитами, а затем в MarkerWithSearch, который находится внутри Map. js .. console.log в MarkerWithSearch забирает массив newPlaces (на один шаг позади, потому что useState используется в Search. js, и это asyn c, как мне было сказано в net), но маркеры не обновляются ..

Карта начинается без маркеров (как newPlaces массив начинается пустым), затем при первом нажатии клавиши в поле поиска он заполняется, но больше никаких изменений не происходит.

Не уверен, почему маркер не обновляется, учитывая, что console.log в том же операторе возврата есть.

import React, { Component, useEffect } from 'react';
import MapWithMarkers from './components/map/Map';
import Navbar from './components/Navbar';

class App extends Component {

  constructor(props) {
    super(props);

      this.state = {
        letters: '',
        newPlaces: [],
        places: [
          {
            name: "PL",
            lat: 51.510228,
            lng: -0.132992,
            type: "alive"
          },...
       ]
    }

      this.searchState=this.searchState.bind(this)
  };

  // set the state of letters to match the Search.js input field
  searchState = (e) => {
    this.setState({letters: e})
    this.searchAdjustedArray();
  }

  // compare the filtered array with the original array in state and kick out the members of state.places that are missing in the filtered array
  searchAdjustedArray = () => {
    const filteredList = this.state.places.filter(club =>
      club.name.toUpperCase().includes(this.state.letters.toUpperCase())
    );
    this.setState ({ newPlaces: filteredList })
  }

  render() {

    return (
      <div>
        <Navbar
          childMethodToChangeState={this.searchState}
        />
        <MapWithMarkers
          markers={this.state.newPlaces}
        />
      </div>
    );
  }
}

export default App;
import React, { useState } from 'react';

const Search = ({ childMethodToChangeState }) => {
    const [text, setText] = useState('')

    const searchChange = (q) => {
        setText(q)
        childMethodToChangeState(q)
    }

    return (
        <section className='search'>
            <form>
                <input
                    type='text'
                    className='form-control'
                    placeholders='Search Clubs'
                    value={text}
                    onChange={(e) => searchChange(e.target.value)}
                    autoFocus
                />
            </form>
        </section>
    )
}

export default Search;
import React from 'react';
import { compose, withProps } from 'recompose';
import { 
    withScriptjs, 
    withGoogleMap, 
    GoogleMap,
    Marker, 
} from 'react-google-maps';

import icon1 from '../map/icon1.svg';
import iconDead from '../map/iconDead.svg';

const API = 'YOUR_API_KEY';

const MapWithMarkers = compose(
    withProps({
        googleMapURL: `https://maps.googleapis.com/maps/api/js?key=${API}&callbak=initMap`,
        loadingElement: <div style={{ height: `100%` }} />,
        containerElement: <div style={{ height: `800px` }} />,
        mapElement: <div style={{ height: `100%` }} />,
    }),
    withScriptjs,
    withGoogleMap,
)((props) =>
        <GoogleMap
            center={{ lat: 51.510228, lng: -0.132992 }}
            zoom={10}
            defaultOptions={{
                styles: mapStyles
            }}
        >
            {props.markers.map((place, index) => {
                return (
                  <div>
                    <MarkerWithSearch
                        index={place.id}
                        position={{ lat: place.lat, lng: place.lng }} 
                        icon={place.type}  
                        place={place}                
                    />
                  </div>                   
                );
            })}
        </GoogleMap>
);


const MarkerWithSearch = (props) => {
 
    return (
      <div>
      <Marker
          position={props.position}
          icon={ props.icon === "alive" ? 
        ({
          url: icon1,
          scaledSize: new window.google.maps.Size(45, 45)
        }) :
        ({
          url: iconDead,
          scaledSize: new window.google.maps.Size(45, 45)
        })}
      >
      </Marker>
      {/* {console.log(props.position)} */}
      </div>
  )
...