繁体   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