React Native中使用async和await的箭头函数

19

我正在尝试在react-native中使用AsyncStorage保存数据。我希望它是异步的,所以使用了asyncawait关键字。

  async onPositiveClickListener = () => {
    // user has completed product tour_end
    try {
      await AsyncStorage.setItem("@ProductTour:key", "true");
      const { navigate } = this.props.navigation;
      navigate("DashboardScreen");
    } catch (error) {
      console.log(error);
    }
  };

保存程序时出现了错误

SyntaxError: Unexpected token, expected ( (40:32)
  38 |   };
  39 | 
> 40 |   async onPositiveClickListener = () => {
     |                                 ^
  41 |     // save user has completed product tour_end
  42 |     try {
  43 |       await AsyncStorage.setItem("@ProductTour:key", "true");
Hide Stack Trace
SyntaxError: Unexpected token, expected ( (40:32)
  38 |   };
  39 | 
> 40 |   async onPositiveClickListener = () => {
     |                                 ^
  41 |     // save user has completed product tour_end
  42 |     try {
1个回答

44

异步命名箭头函数应该像这样声明:

const onPositiveClickListener = async () => {
    // user has completed product tour_end
    try {
      await AsyncStorage.setItem("@ProductTour:key", "true");
      const { navigate } = this.props.navigation;
      navigate("DashboardScreen");
    } catch (error) {
      console.log(error);
    }
  };

AsyncStorage有三个参数,键和值都是字符串,还有一个回调函数,因此只能使用AsyncStorage设置字符串。但您可以使用JSON.stringify(obj)将其他数据类型转换为字符串,并在检索后解析它,这样就可以保存任何其他数据类型。 - Shubham Khatri

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接