簡體   English   中英

[未處理的承諾拒絕:類型錯誤:未定義不是對象(評估“response.data”)]

[英][Unhandled promise rejection: TypeError: undefined is not an object (evaluating 'response.data')]

作為 React Native 項目的一部分,我有一個非常簡單的 Fetch API 調用。 我似乎能夠接收響應數據(通過 Console.log() 驗證),但由於某種原因,我的數據沒有正確傳輸到 useState() 中。 我以前在做這件事時沒有遇到任何困難。

這是我嘗試存儲數據的地方:

const [data, setData] = useState("");

這是我的 API 調用:

            fetch('https://api.panodime.com/v1/oauth-login?email=' + email + '&token=' + token, {
                headers: { 'X-ApiKey': 'doxy08E9SqxTvgvFpB3yOEGCO4YE77m88iSXTQ5TZrcpf3Qw' }
            })
                .then((response) => { return response.json() })
                .then((response) => { console.log(response.data.authToken)})
                .then((response) => setData(response.data.authToken))
                //.then(() => console.log(data))
                //.then(() => storeData(data))
                //.catch((error) => console.error(error))

我用於 fetch API 調用的輸入參數的測試數據是email: hannah89orpington@gmail.comtoken: 235906121209210

最奇怪的是.then((response) => { console.log(response.data.authToken)})成功返回了我想要的 authToken,但是當我在.then((response) => setData(response.data.authToken))調用它時.then((response) => setData(response.data.authToken)) ,它說它是未定義的。 任何幫助,將不勝感激。

您正在使用extra then作為響應。 嘗試這個

fetch('https://api.panodime.com/v1/oauth-login?email=' + email + '&token=' + token, {
                headers: { 'X-ApiKey': 'doxy08E9SqxTvgvFpB3yOEGCO4YE77m88iSXTQ5TZrcpf3Qw' }
            })
     .then((response) => { return response.json() })
     .then((response) => { 
      console.log(response.data.authToken);
      setData(response.data.authToken) // do here
     })
     .then((response) => setData(response.data.authToken)) // remove this

這是 Promise 和 Thenables 的簡短課程。

如果你想有多個像這樣的 thenables,你需要確保你返回值,所以它可以傳遞給下一個函數。

例如

.then((response) => { 
     console.log(response.data.authToken)
     return response //this pass response to next function
 })
.then((response) => setData(response.data.authToken))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM