【问题标题】:Updating state before rendering (React)渲染前更新状态(React)
【发布时间】:2018-04-17 09:44:42
【问题描述】:

我已经绞尽脑汁想解决一个问题好几个小时了。基本上,我希望在渲染组件之前 更新状态中的 markersList 属性。假设markerList 填充了Google Maps 标记,这些标记在initMap() 方法中被推入数组。但是当我在渲染方法中控制台记录数组时,数组是空的。在渲染方法完成之前,我只需要有关如何使用所有标记更新数组的帮助。我希望我的要求是有道理的。谢谢大家!

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      map: "",
      marker: "",
      markersList: [],
      locations: [
        {
          title: "Powell's Books",
          address: "1005 W Burnside St, Portland, OR 97209",
          coordinates: {
            lat: 45.523096,
            lng: -122.681354
          }
        },
        {
          title: "Ground Kontrol",
          address: "511 NW Couch St, Portland, OR 97209",
          coordinates: {
            lat: 45.523943,
            lng: -122.675872
          }
        },
        {
          title: "Portland Art Museum",
          address: "1219 SW Park Ave, Portland, OR 97205",
          coordinates: {
            lat: 45.51615,
            lng: -122.683357
          }
        },
        {
          title: "Roseland Theater",
          address: "8 NW 6th Ave, Portland, OR 97209",
          coordinates: {
            lat: 45.52328,
            lng: -122.676297
          }
        },
        {
          title: "Voodoo Doughnuts",
          address: "22 SW 3rd Ave, Portland, OR 97204",
          coordinates: {
            lat: 45.522713,
            lng: -122.672944
          }
        },
        {
          title: "Arlene Schnitzer Concert Hall",
          address: "1037 SW Broadway, Portland, OR 97205",
          coordinates: {
            lat: 45.517197,
            lng: -122.681419
          }
        },
        {
          title: "Pioneer Place",
          address: "700 SW 5th Ave, Portland, OR 97204",
          coordinates: {
            lat: 45.518335,
            lng: -122.677261
          }
        }
      ]
    }
  }
  componentDidMount() {
    this.initMap();
  }

  initMap = () => {
    const map = document.querySelector(".map");

    let newMap = new window.google.maps.Map(map, {
      center: {
        lat: 45.519692,
        lng: -122.680496,
        mapTypeControl: false
      },
      zoom: 16
    });

    let infoWindow = new window.google.maps.InfoWindow();
    let locations = this.state.locations;
    let bounds = new window.google.maps.LatLngBounds();


    for (let i = 0; i < locations.length; i++) {

      let wikiUrl = "https://en.wikipedia.org/w/api.php?action=opensearch&origin=*&search=" + this.state.locations[i].title + "&format=json";

      let newMarker = new window.google.maps.Marker({
        map: newMap,
        position: locations[i].coordinates,
        title: locations[i].title,
        animation: window.google.maps.Animation.DROP
      });
      this.state.markersList.push(newMarker); 
      bounds.extend(newMarker.position);
      newMarker.addListener("click", function () {
        infoWindow.open(map, this);
        newMap.panTo(newMarker.position);
        axios.get(wikiUrl)
          .then(response => {
            const wikiInfo = response.data;

            infoWindow.setContent(`<p><strong>${wikiInfo[0]}</strong><br>${locations[i].address}</p><p>${wikiInfo[2][0]}</p><p>Click <a href='${wikiInfo[3][0]}' target='_blank'><strong>HERE</strong></a> for more information on ${wikiInfo[0]}.</p>`)
          })
      })

    }
    newMap.fitBounds(bounds);
  }

  render() {
    return (
      <div>
        <div className="menu">
          <SearchInput />

          <ul className="location-list" >
          {console.log(this.state.markersList)}
          {
          }
          </ul>
        </div>
        <div className="map">

        </div>
      </div>

    );
  }
}

【问题讨论】:

    标签: reactjs google-maps


    【解决方案1】:

    您是否尝试过拨打componentWillMount 而不是componentDidMount

    【讨论】:

    • 是的,我做到了,它只是给了我一个错误:“TypeError: Cannot read property 'firstChild' of null.”
    • 啊,我想我看到了一个问题。坚持使用componentDidMount,但是当您尝试推送markersList 时,看起来您正在直接改变状态。执行let tempArray = this.state.markersList 之类的操作,然后推送到 tempArray 并将markersList 状态设置为 tempArray
    • 我确实试过了。当我控制台登录渲染方法时,它会记录两次markersList,第一次是在填充tempArray之前它是空的,第二次是在填充它时。在填充标记列表后,我需要它渲染一次。
    猜你喜欢
    • 2021-01-17
    • 2016-11-04
    • 2017-01-01
    • 2018-10-03
    • 2020-12-18
    • 2021-07-09
    • 2020-10-24
    • 1970-01-01
    相关资源
    最近更新 更多