React Native-提取似乎不会触发

时间:2019-09-26 06:04:55

标签: javascript reactjs react-native fetch

获取似乎没有触发-这是我在React Native中的组件:

import { Button } from 'react-native';

export function Test() {
  function submit() {
    console.log('submit');
    fetch('https://swapi.co/api/people/1/').then(
      res => {
        console.log('res', res);
        return res.json();
      },
      err => console.log('err', err)
    ).then(
      res => console.log('res', res)
    ).catch(
      err => console.log('catch', err)
    ).finally(
      res => console.log('finally', res)
    );
    console.log('after');
  }
  return (
    <Button
      title="Test"
      onPress={submit}
    />
  );
}

我在控制台中唯一看到的是:

submit
after

我也尝试过Axios,结果是一样的。

Android和IOS均会发生此问题...


编辑

只需尝试使用XMLHttpRequest api,再一次,只有submit日志:

function submit() {
  console.log('submit');
  var request = new XMLHttpRequest();
  request.onreadystatechange = (e) => {
    console.log('ready', e);
    if (request.readyState !== 4) {
      return;
    }
    if (request.status === 200) {
      console.log('success', request.responseText);
    } else {
      console.warn('error');
    }
  };
  request.open('GET', 'https://swapi.co/api/people/1/');
  request.send();
}

2 个答案:

答案 0 :(得分:1)

onPress={() => this.submit()}

答案 1 :(得分:0)

原始代码

function submit() {
    console.log('submit');
    fetch('https://swapi.co/api/people/1/').then(
      res => {
        console.log('res', res);
        return res.json();
      },
      err => console.log('err', err)
    ).then(
      res => console.log('res', res)
    ).catch(
      err => console.log('catch', err)
    ).finally(
      res => console.log('finally', res)
    );
    console.log('after');
  }

修改如下

async function submit() {
    console.log('submit');

    await fetch('https://swapi.co/api/people/1/')
        .then(res => res.json())
        .then(resJson => console.log('res ', resJson))
        .catch(err => console.log('catch ', err))
        .finally(() => console.log('finally'));

    console.log('after');
}

因此控制台中将显示以下结果:

submit
res {name: "Luke Skywalker", height: "172", mass: "77", hair_color: "blond", skin_color: "fair", …}
finally
after