首页 > 解决方案 > 在 React Native 中处理 API 调用?

问题描述

我是本机反应的新手,并试图与我在我的一个屏幕文件中创建的 API 帮助程序进行交互,我确信这是一个语法错误,但我也很感兴趣它的架构是否正确,因为我来了形成iOS开发。

有错误的函数:

  handleLoginPress = () => {
    ApiHelper.loginDriver(this.state.email, this.state.password)
      .then((result) => {
        console.log(result);
    }).catch((error) => {
        console.log("error is " + error);
    });
  };

错误是:

“void”类型上不存在属性“then”

它的调用函数:

static loginDriver(username: string, password: string) {
    fetch('http://localhost:8080/drivers/login', {
         method: 'POST',
    headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
    },
    body: JSON.stringify({
        uername: username,
        password: password,
    }),
    });
}

我的想法是需要对 apis 登录函数的返回类型进行一些规范吗?

标签: typescriptreact-native

解决方案


您的 loginDriver 函数中缺少 return,请添加 return 语句以返回数据。

static loginDriver(username: string, password: string) {
  return fetch('http://localhost:8080/drivers/login', {
    method: 'POST',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      uername: username,
      password: password
    })
  });
}

推荐阅读