簡體   English   中英

反應-將狀態傳遞給父組件-太多AXIOS請求

[英]React - Passing state to parent component - too many AXIOS requests

我是編程和React的初學者,我必須創建一個運行正常的Google Map單頁網站。 我正在使用google-map-react。
我有一個父App.js(包含對的調用和HTML邊欄)和一個子Map.js,其中包含了地圖本身和axios請求功能。 我正在發出axios請求,以從foursquare api獲取數據。 它沒有副作用。 然后,我想將這些數據傳遞到我的app.js並更新父狀態,以便可以在邊欄上呈現位置。
這是我使用的功能(在Map.js中)。 我不得不將調用作為最后的資源放入componentWillReceiveProps中,因為componentDidMount不起作用:

https://jsfiddle.net/kd1yuhe5/

我認為這可能是問題所在,但這也是我發現顯示該列表的唯一方法:

this.props.updateVenues(this.state.venues)

這是來自App.js的代碼

    updateVenues(venues) {
    this.setState({
        venues: venues,
    });
}

然后我調用了這樣的方法:

<Map updateVenues={this.updateVenues.bind(this)} />

該代碼有效,場地顯示在側邊欄中(如果您需要該代碼,請告訴我,但我認為這無關緊要),但是我會不斷提出要求,直到超出配額為止。 再說一遍:我是一個初學者。 我是3個月前剛開始的​​。

編輯:這兩個組件:
Map.js
https://jsfiddle.net/kd1yuhe5/5/

App.js
https://jsfiddle.net/xwzrm4bp/2/

當React組件的狀態被更新(並且沒有componentShouldUpdate的自定義實現)時,它會觸發該組件的重新渲染(即調用render函數)。

如果自上次渲染以來此組件的子代的props已經更改,它們也將重新渲染。

他們重新渲染是因為他們已經收到了新的道具,這也將調用其componentWillReceiveProps函數。

由於您是在Map每次收到道具時都在獲取數據,因此您每次在App上發生任何更改(狀態更改)時都在獲取數據。

首先在Map.js中,將this.props.query分配給this.state.query 這看起來像一個錯誤,因為在這種情況下,您想要的是componentWillReceiveProps接收的新道具,這是此函數的第一個參數。 因此,您應該將props.query分配給this.state.query

除了實際上您不應:

this.state.query僅在componentWillReceiveProps中使用,因此無需將props.query放入state.query。

其次,由於您同時具有以前的props更新中的this.props.query和作為新接收到的查詢的props.query,因此您只有在查詢實際更改時才有機會獲取:

// Receive the update query from parent and fetch the data
componentWillReceiveProps(nextProps){
    if (this.props.query !== nextProps.query) {
        this.fetchData(nextProps.query);
    }
}

現在,您可能會問:“好吧,為什么我的Map組件總是重新渲染,即使它的道具沒有改變也是如此”。

但是他們做到了:在App.js中

<Map 
    query={this.state.query}
    center={this.state.center}
    updateVenues={this.updateVenues.bind(this)}
    getClickedMarker={this.getClickedMarker.bind(this)}
/>

通過調用this.updateVenues.bind(this)this.getClickedMarker.bind(this)的渲染方法,您正在創建的updateVenues和getClickedMarker道具新值(實際上是新功能的引用),在每個渲染。

相反,您應該將這些方法綁定到App的構造函數中:

constructor(props) {
    super(props);
    this.updateVenues = this.updateVenues.bind(this);
    this.getClickedMarker = this.getClickedMarker.bind(this);
    ....
}

....
<Map 
    query={this.state.query}
    center={this.state.center}
    updateVenues={this.updateVenues}
    getClickedMarker={this.getClickedMarker}
/>

這可能會限制您的API調用很多,也可以將它們反跳

暫無
暫無

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

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