React-Native - 访问componentDidMount之外的函数

时间:2018-02-16 09:20:36

标签: javascript function react-native scope

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);
      }
    );
  }

1 个答案:

答案 0 :(得分:2)

我将假设你创建getArrival的代码在你的类体内是,例如: (你' ve confirmed that now

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

    componentDidMount() {
        // ...
    }

    // ...
}

如果是,那就是使用类属性提议(尚未标准,但在第3阶段),它会在您的实例上创建一个属性(如构造函数中的this.getArrival = ...;)。

所以你可以在this上访问它:

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

该代码处于回调(或两个)中,但它们似乎都是箭头函数,因此它们会关闭this并将使用调用的componentDidMount(这是正确的一个)。

请参阅this question's answers,了解我为什么检查回调是否为箭头函数,以及在出于某种原因无法使用箭头函数时如何处理。