我试图编写一个递归显示ActionSheetIOS的方法,从数组中 Select 一个值并返回所选值:

async function _rescursiveSelect(data, index) {
  if (index < data.length) {
    const object = data[index];

    if (object.array.length === 1) {
      return await _rescursiveSelect(data, index + 1);
    }

    ActionSheetIOS.showActionSheetWithOptions({
      title: 'Choose a value from array: ',
      options: object.array,
    },
    buttonIndex => async function() {
      const selectedValue = data[index].array[buttonIndex];
      data[index].value = selectedValue;
      delete data[index].array;

      return await _rescursiveSelect(data, index + 1);
    });
  } else {
    return data;
  }
}

不幸的是,当我调用这个方法时,它返回undefined.我猜问题来自异步/等待使用,但我还没有解决.

有什么建议吗?

推荐答案

它返回undefined,因为路径中没有return语句.async-await模式适用于异步函数,但ActionSheetIOS.showActionSheetWithOptions不是异步的.

异步函数只是一个返回Promise的函数.async关键字只是一种语法糖,可以让异步代码可读,并隐藏了它背后的promise 处理.

幸运的是,这种旧式的库可以轻松地使用异步回调函数:

function showActionSheetWithOptionsAsync(options) {
    return new Promise(resolve => { 
        // resolve is a function, it can be supplied as callback parameter 
        ActionSheetIOS.showActionSheetWithOptions(options, resolve);
    });
}

async function _rescursiveSelect(data, index) {
    if (index < data.length) {
        const object = data[index];

        if (object.array.length === 1) {
            return await _rescursiveSelect(data, index + 1);
        }

        const buttonIndex = await showActionSheetWithOptionsAsync({
            title: 'Choose a value from array: ',
            options: object.array
        });
        const selectedValue = data[index].array[buttonIndex];
        data[index].value = selectedValue;
        delete data[index].array;
        return await _rescursiveSelect(data, index + 1);
    } else {
        return data;
    }
}

React-native相关问答推荐

Redux将旧状态迁移到新状态

如何在Reaction Native DrawerNavigation中添加注销功能

ios 中节列表中的scrollToLocation 不起作用.在 Android 上,列表滚动回索引 0,但在 ios 上不会发生同样的情况

在 React Native 上为 android 创建自定义 UI 组件,如何向 JS 发送数据?

React Native 白色黑屏问题

在 LTR 设备上强制 RTL

react native foreach 循环

react-native 链接仅适用于一个项目(Android 或 iOS)

React-native 组件的 elevation样式导致的阴影

自从升级到 Xcode 10.2 我不能再通过 cli 运行 react-native run-ios

React Native - SectionList numColumns support

路由状态没有通过 redux 保持在 react-native

更改默认的 React Native 下拉箭头图标

React Native 得到这个错误'Unrecognized operator abs'

React Native Bullet Character? or Unicode?

在 React 中调用 getDerivedStateFromProps 中的方法

React Native:使用百分比时将视图的宽度设置为等于其高度

React Native font outline / textShadow

React Native:如何动态更改

如何在 React Native 中强制禁用 iOS 暗模式