【问题标题】:Can't access JSON attribute.无法访问 JSON 属性。
【发布时间】:2017-03-30 19:17:26
【问题描述】:
alert(fetch('https://facebook.github.io/react-native/movies.json')  
    .then(function(response) {
        return response.json()['description']
    }))

我期待Your app fetched this from a remote endpoint!,但显然这只是一个对象?

根据我检查过的其他答案,例如this one,这应该可以完美运行。

【问题讨论】:

    标签: javascript react-native


    【解决方案1】:

    response.json 返回一个Promise

    .then(function(response) {
        return response.json()
    })
    .then(function(data) {
       return data.description
    })
    .then(function(description) {
        alert(description)
     })
    

    【讨论】:

    • 在这之前有多少个左括号/大括号?第 3 行有 2 个括号,但另一个 then 语句例如只有 1 个,并且没有分号。
    • 还是比回调地狱好。顺便说一句,如果不太关心旧浏览器,您可以使用箭头功能。 fetch(blah).then(x => x.json()).then(data => alert(data.description)) - 根本没有括号:)
    • 所以没有办法从那里取出数据?我想将它保存为变量并在我的代码中的其他地方使用它。
    • 您可以将 Promise 保存为变量,例如 gettingData = fetch().then(x => x.json()),然后在知道它是 Promise gettingData.then(data => /* do something with data*/) 的情况下使用它。请阅读这个问题以更好地了解异步代码的问题是关于stackoverflow.com/questions/14220321/…
    【解决方案2】:

    您可以访问如下所示的说明。

    要保存该值并在以后使用它,您可以使用状态(也称为组件状态)。

    .then(function(response) {
        var resJson = response.json();
        var des = resJson['description'];
        this.setState(
             { 
                 description: des 
             }
        )
    
        }))
    

    你可以像这样在 React 组件中定义你的状态:

    class MyClass extends Component {
    
        state = {
            description: ""
        }
    

    然后像这样检索状态:

    var currentState = this.state.description;
    

    【讨论】:

      猜你喜欢
      • 2018-04-24
      • 1970-01-01
      • 1970-01-01
      • 2016-07-12
      • 2023-03-20
      • 2011-11-05
      • 2014-09-19
      • 2012-12-01
      • 2017-04-25
      相关资源
      最近更新 更多