2017-08-10 91 views
0

我需要將responseJson.result(JSON對象)轉換爲數據(JS對象)。
當我使用控制檯日誌或提醒它的返回未定義。我無法將json對象轉換爲JS對象

我不知道什麼是錯 - 關於控制檯日誌或警報方法或stringify?

constructor() { 
    super(); 
    this.state = { 
    data: null, 
    }; 
} 

componentWillMount() { 
    return fetch("www.abc.xyz/api") 
    .then((response) => response.json()) 
    .then((responseJson) => { 
     let ds = new ListView.DataSource({ 
     rowHasChanged: (r1, r2) => r1 !== r2 
     }); 

     this.setState({ 
     data: JSON.stringify(responseJson.result), 
     }, function() { 
     }); 

     var resultJ = this.state.data.result; 
     alert(resultJ); 
    }) 
    .catch((error) => { 
     alert("0 : Recrods On This Module ") 
    }); 
} 
+0

''console.log(responseJson)'''setState'say''之前有什麼? – Nocebo

+0

來自responseJson的數據源它在listview上工作。 但我想轉換responseJson到數據並設置數據在Listview –

回答

0

setState呼叫是異步的,這意味着狀態值立即不可用。您已在setState集中有回調參數。你只需要使用它,例如

this.setState({ 
    data: JSON.stringify(responseJson.result), 
}, function() { 
    var resultJ = this.state.data.result; 
    alert(resultJ); 
}); 
+0

後嘗試此操作。它的返回undefined :(爲什麼不工作 –