[英][Unhandled promise rejection: TypeError: undefined is not an object (evaluating 'response.data')]
I have a very simple Fetch API call as part of a React Native project.作为 React Native 项目的一部分,我有一个非常简单的 Fetch API 调用。 I'm seemingly able to receive the response data (verified with Console.log()), but for some reason, my data isn't being transferred into useState() properly.
我似乎能够接收响应数据(通过 Console.log() 验证),但由于某种原因,我的数据没有正确传输到 useState() 中。 I haven't had any difficulties doing this before.
我以前在做这件事时没有遇到任何困难。
This is where I'm trying to store my data:这是我尝试存储数据的地方:
const [data, setData] = useState("");
And this is my API call:这是我的 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))
The test data I'm using for the input parameters to the fetch API call are email: hannah89orpington@gmail.com
and token: 235906121209210
.我用于 fetch API 调用的输入参数的测试数据是
email: hannah89orpington@gmail.com
和token: 235906121209210
。
The strangest thing is that the line .then((response) => { console.log(response.data.authToken)})
returns the authToken that I want successfully, but when I call it in .then((response) => setData(response.data.authToken))
, it says that it's undefined.最奇怪的是
.then((response) => { console.log(response.data.authToken)})
成功返回了我想要的 authToken,但是当我在.then((response) => setData(response.data.authToken))
调用它时.then((response) => setData(response.data.authToken))
,它说它是未定义的。 Any help would be appreciated.任何帮助,将不胜感激。
You are using extra then
in response.您正在使用
extra then
作为响应。 Try this尝试这个
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
This is a short lesson for Promise and Thenables.这是 Promise 和 Thenables 的简短课程。
If you want to have multiple thenables like this, you need to ensure you return the value, so it can be pass on to the next function.如果你想有多个像这样的 thenables,你需要确保你返回值,所以它可以传递给下一个函数。
eg例如
.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.