【问题标题】:Fetch someUrl.html not working in React Native / Expo?获取 someUrl.html 在 React Native / Expo 中不起作用?
【发布时间】:2018-10-18 05:53:30
【问题描述】:

我正在尝试使用 fetch 在 React Native 中获取 HTML 页面的内容,我正在 expo 上运行它,这里:

https://snack.expo.io/@abalja/hellofetch

基本上,代码没有什么特别之处,它使用“fetch”来加载 .json 文件,但我无法让它用于 .html 文件。它只是默默地失败,我什至没有记录错误。我不确定这是 Expo 还是 ReactNative 问题。

const url2 = 'http://www.spiegel.de/sport/fussball/nations-league-italien-trifft-in-der-nachspielzeit-polen-steigt-ab-a-1233219.html#ref=rss'

export default class App extends React.Component {
  componentDidMount(){

    console.log('did mount, fetching: ' + url2)
    fetch(url2)
        .then((response) => {
          console.log(response) // 1
          return response.text()
        })
        .then((responseText) => {
          console.log('fetch text', responseText) // 2
          // return responseText.movies;
        })
        .catch((error) => {
          console.error(error);
        });
  }
  render() {
    return (
      <View style={styles.container}>

      </View>
    );
  }
}

在 1 时,我记录了响应:

{type:"default",status:200,ok:true,headers:{…},url:"http://www.spiegel.de/sport/fussball/nations-league-italien-trifft-in-der-nachspielzeit-polen-steigt-ab-a-1233219.html",_bodyInit:{…},_bodyBlob:{…}}
type:"default"
status:200
ok:true
►headers:{map:{…}}
url:"http://www.spiegel.de/sport/fussball/nations-league-italien-trifft-in-der-nachspielzeit-polen-steigt-ab-a-1233219.html"
►_bodyInit:{_data:{…}}
►_bodyBlob:{_data:{…}}

在 2 时,我完全没有记录任何内容。

【问题讨论】:

  • 我无法重现错误,我得到了记录的响应和文本。您能否提供有关您想从该网站检索的内容的更多信息?
  • 您是在 expo 上还是在设备上尝试过?

标签: react-native fetch expo


【解决方案1】:

Promise 语法让我很困惑,所以我改成了 async-await:

async componentDidMount() {
    console.log('did mount, fetching: ' + url2);
    try {
        let response = await fetch(url2);
        let text = await response.text();
        console.log(text)
   } catch(e) {
        console.log(e)
   }
}

有效!你可以在这里查看:https://snack.expo.io/@aazwar/fetch-url

【讨论】:

  • console.log(text) 仍然什么都不做,但是文本出现在 UI 中。这是为什么呢?
  • 我刚刚意识到 console.log(text) 什么都不做,但它甚至没有记录“did mount, fetching”
  • 这对我有用。我忘记了'let text = await response.text()'。
【解决方案2】:

这是因为您将Response 解析为text 而不是json,然后尝试针对string 调用object-key。基本上你当时拥有的是看起来像 json 的字符串。请改用.json()-method 解析您的回复。

return response.text() 因此应该是return response.json()

重构你的代码

// With .then()
fetch(url2)
    .then((response) => {
      return response.json()
    })
    .then((responseJson) => {
      return responseJson.movies;
    })
    .catch((error) => {
      console.error(error);
    });

// OR with await/async
const response = await fetch(url2)
const json = await response.json() // As '.json()' is async function as well
return json.movies

我会成功使用 await/async,因为语法更简洁,而且它开始成为一种方式。

【讨论】:

    猜你喜欢
    • 2020-11-15
    • 2020-07-11
    • 2020-11-20
    • 2018-12-25
    • 1970-01-01
    • 2022-12-29
    • 2022-12-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多