嵌套的回调函数(React本机JS)

时间:2019-11-15 13:28:36

标签: reactjs react-native google-maps expo

我有几个不同的功能,可以帮助设置组件的不同状态,并且我希望彼此依次运行这些功能。我知道上面有多个帖子,但是它们似乎主要是为了在一个函数之后另一个函数的运行而提供的,但是我需要依次执行两个以上的函数

所需订单

1)设置起始和最终目的地的状态

2)运行this.getDirections()(此函数设置arrOfPolylines的状态,我希望通过resetRouteSelectionStatus()进行重置)

3)运行resetRouteSelectionStatus()

4)运行这些功能后,我希望有一个空的this.state.arrOfPolylines

实际结果

代码中没有错误,但是由于没有打印控制台日志,因此不会输入resetRouteSelectionStatus()。有人可以引导我走正确的道路吗?

    <Button
  onPress={() => { //on button press set final destination and starting location
    {
      (this.state.tempDestination.longitude != null && this.state.tempStarting.longitude != null) &&
        this.setState({
          finalDestination: {
            latitude: this.state.tempDestination.latitude,
            longitude: this.state.tempDestination.longitude,
          },
          startingLocation: {
            latitude: this.state.tempStarting.latitude,
            longitude: this.state.tempStarting.longitude,
          }
        }, () => {
              this.getDirections((this.state.startingLocation.latitude + "," + this.state.startingLocation.longitude), (this.state.finalDestination.latitude + "," + this.state.finalDestination.longitude),
              () => {this.resetRouteSelectionStatus()});
            }
            );

        }
      }}
      title="Determine Directions"
      color="#00B0FF"

      resetRouteSelectionStatus() {
    console.log('entered reset route selection status function')
    this.setState({arrOfPolyline: null }, () => {console.log("i should be null nd come first" + this.state.arrOfPolyline)}) ;
    this.setState({ selectChallengeStatus: null });
    this.setState({ userRouteSelectionStatus: null }); //when user click on button set seleection status to 0 so route options will be displayed again after generation new route
    //this.setState({arrOfDirectionDetails: []}); // clear past direction details when user select generate route with new  starting/ending location
    // clear past poly lines when user has selected new routes
    //console.log("everything has been reset");
  }




async getDirections(startLoc, destinationLoc) {
    let resp = await fetch(`https://maps.googleapis.com/maps/api/directions/json?origin=${startLoc}&destination=${destinationLoc}&key="KEY"&mode=driving&alternatives=true`)
    let respJson = await resp.json();
    let routeDetails = respJson.routes;
    let tempPolyLineArray = [];
    let tempDirArrayRoute = [];
    //console.log(startLoc);
    //console.log(destinationLoc);
    for (i = 0; i < routeDetails.length; i++) // respJson.routes = number of alternative routes available
    {
      let tempDirArray = []; // at every new route, initalize a temp direction array
      let points = Polyline.decode(respJson.routes[i].overview_polyline.points);
      let coords = points.map((point, index) => {
        return {
          latitude: point[0],
          longitude: point[1]
        }
      })
      tempPolyLineArray.push(coords);
      for (k = 0; k < routeDetails[i].legs[0].steps.length; k++) // for each route go to the correct route, enter legs ( always 0), get the number of instruction for this route
      {
        //console.log (routeDetails[i].legs[0].steps[k])
        tempDirArray.push(routeDetails[i].legs[0].steps[k]) // push all instructions into temp direction array
        //this.state.arrOfDirectionDetails.push(routeDetails[i].legs[0].steps[k]); // for each instruction save it to array
      }
      tempDirArrayRoute.push(tempDirArray); // at the end of each route, push all instructions stored in temp array as an array into state  
    }
    this.setState({ arrOfDirectionDetails: tempDirArrayRoute });
    this.setState({ arrOfPolyline: tempPolyLineArray });
    //creating my html tags
    let data = [];
    let temptitle = "Route ";
    for (let j = 0; j < routeDetails.length; j++) {
      data.push(
        <View key={j}>
          <Button
            title={temptitle + j}
            onPress={() => this.updateUser(j)}
          />
        </View>
      )
    }
    this.setState({ routebox: data })

  }

2 个答案:

答案 0 :(得分:1)

这里要注意几件事:

  1. 我将onButtonPress函数的内联函数提取到async函数中

类似的东西:

const onButtonPressHandler = async () => {
 ... put your code here
}

然后,您将onButtonPress修改为:

<Button
  onPress={this.onButtonPressHandler}
  ... rest of your props here
 />

然后您可以在buttonPress处理程序中正确使用async / await。

  1. setState函数不是同步函数。如果您立即依赖结果,将会感到失望。

每次致电setState都可以触发重新提交。

相反,我会在末尾将所有setState呼叫合并为一个呼叫。

答案 1 :(得分:0)

getDirections函数不包括回调,而应该包括:

async getDirections(startLoc, destinationLoc, callback) {
.....
 this.setState({ routebox: data },callback());
}

或不确定是否会按顺序:

async () => {
              await this.getDirections((this.state.startingLocation.latitude + "," + this.state.startingLocation.longitude), (this.state.finalDestination.latitude + "," + this.state.finalDestination.longitude) );
             this.resetRouteSelectionStatus();
            }

您可能需要将resetRouteSelectionStatus编辑为:

resetRouteSelectionStatus = async ()=>{