簡體   English   中英

React-Native —在componentDidMount之外訪問函數

[英]React-Native — Accessing functions outside componentDidMount

componentDidMount內部調用函數時,我遇到了范圍問題。 函數getArrivalcomponentDidMount外部定義。 我嘗試了幾件事但沒有成功。

定義getArrival以便我可以在componentDidMount內部訪問它的正確方法是什么?

先感謝您。

碼:

getArrival = (lines) => {
    return fetch('https://api.tfl.gov.uk/Line/' + lines + '/Arrivals/' + nearestStopId)
      .then((response) => response.json())
      .then((arrivalData) => {

        }, function() {
          // do something with new state
        });
        console.log(arrivalData);
      })
      .catch((error) => {
        console.error(error);
      }
    );
  }

  componentDidMount() {
    // Variable to store user data
    let userLines = null

    // Variable to store nearest stop id
    let nearestStopId = null

    // Check all variables against the API
    for (i = 0; i < apidata.length; i++) {

      // Checks user stops id against beacon id
      if (userdata[i].bustopId == beaconId) {
        // Store match into variable
        nearestStopId = userdata[i].bustopId
        userLines = userdata[i].buses

        // matchStop(nearestStopId)

        break // Breaks the loop
      }
      console.log(userLines)
    }

    // Data for stops
    return fetch('https://api.tfl.gov.uk/StopPoint/' + nearestStopId )
      .then((response) => response.json())
      .then((stopData) => {

        let linesId = []
        let selectedLines = []

        console.log("linesId at this stop", stopData.lines)
        console.log("userlines", userLines)

        // Loop through the data in stopData
        for (i = 0; i < stopData.lines.length; i++) {
          // ... and add all buses id from the API to the array
          let currentLine = stopData.lines[i].id
          linesId.push(currentLine)

          // Checks if user lines are included in current lines ...
          if ( userLines.includes(currentLine) ) {
            // ... if so, push it into selected lines
            selectedLines.push(currentLine)

            getArrival(lines) // This gets an error not defined

            let lines = selectedLines.toString()
          }
        }

        console.log("selectedLines", selectedLines, "from ", linesId)

        let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        this.setState({
          isLoading: false,
          dataSource: ds.cloneWithRows(selectedLines),
        }, function() {
          // do something with new state
        });
      })
      .catch((error) => {
        console.error(error);
      }
    );
  }

我將假設您顯示的創建getArrival的代碼位於您的類主體中,例如:( 現在已經確認

class YourComponent extends React.Component {
    getArrival = () => {
        // ...
    };

    componentDidMount() {
        // ...
    }

    // ...
}

如果是這樣,那將使用類屬性建議(不是標准的,但是在階段3),並在您的實例上創建一個屬性(如構造函數中的this.getArrival = ...; )。

因此,您可以在this訪問它:

    this.getArrival(lines)
//  ^^^^^

該代碼在一個(或兩個)回調中,但是它們似乎都是箭頭函數,因此它們都關閉了this函數,並將使用與之一起調用的一個componentDidMount (這是正確的)。

請參閱此問題的答案,以了解為什么我檢查了回調是箭頭函數,以及在由於任何原因而無法使用箭頭函數的情況下該怎么辦。

暫無
暫無

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

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