2015-05-05 22 views
8

我正在使用反應本機編寫iPhone的小應用程序。我正嘗試使用fetch從網站獲取JSON數據。像這樣的例子:如何從提取獲取JSON數據(react-native)

function status(response) { 
    if (response.status >= 200 && response.status < 300) { 
    return response 
    } 
    throw new Error(response.statusText) 
} 

function json(response) { 
    return response.json() 
} 


fetch('/users', { 
    method: 'post', 
    headers: { 
    'Accept': 'application/json', 
    'Content-Type': 'application/json' 
    }, 
    body: JSON.stringify({ 
    name: 'Hubot', 
    login: 'hubot', 
    }) 
}).then(status) 
    .then(json) 
    .then(function(json) { 
    console.log('request succeeded with json response', json) 
    }).catch(function(error) { 
    console.log('request failed', error) 
    }) 

一切工作正常,但我需要稍後使用該數據。當我嘗試將它分配給json函數中的某個變量時,我收到「請求錯誤」,然後獲取數據(正確)。獲取這些數據的最佳做法是什麼,並在稍後將其用於某些變量中?

回答

5

您可以在組件的構造函數創建一個變量:

constructor(props) { 
    super(props); 
    this.state = { 
     jsonData: '' 
    } 
} 

,當你需要則進行更新這個變量:

.then((responseData) => { 
    this.setState({ 
     jsonData: responseData 
    }); 
    }) 
+3

,則通常有兩個thens這樣的:'。然後((響應)=> { response.text(); 的console.log(響應); }) 。然後((responseText的)=> { 的console.log(responseText的); }) .catch((誤差)=> { console.warn(誤差); }) .done();'我想知道什麼那麼兩人中的每一個人都會回來嗎?爲什麼這樣組織?他們如何工作? –

+1

@KevinZhao:2然後順序執行,第1個是從響應對象中獲取文本,第二個是打印文本值。 – vignesh

0

就我而言,我使用了sails.js與當地護照但它與任何其他node.js框架非常相似,可以捕獲這些用於簽名函數(req,res)的變量,其中的變量存儲在req.body中。在你的情況下,req.body.name將包含'Hubot',req.body.login將包含'hubot'.Response將使用res.send發送。檢查node.js文檔以獲取更多詳細信息。

5

我是這樣做的。我在控制檯上顯示響應。您可以根據需要將響應數據存儲在狀態變量或本地存儲中。

doSignUp() { 

    console.log("inside post api"); 
    fetch('your API URL', { 
    method: 'POST', 
    headers: { 
        'Accept': 'application/json', 
        'Content-Type': 'application/json', 

       }, 


     body: JSON.stringify({ 
     password: this.state.password, 
     email:this.state.email, 
     name: this.state.firstname, 
     last_name :this.state.last_name, 
     mobile:this.state.mobile, 
     ssn:"2222222" 

    }) 
     }).then((response) => response.json()) 
     .then((responseData) => { 
           console.log("inside responsejson"); 
           console.log('response object:',responseData) 

     }).done(); 
    } 
在fetch方法