如何解构javascript用户对象以显示在帐户页面上



我无法从数据库中获取帐户屏幕以显示用户详细信息。我可以将用户详细信息作为一个对象获取,但我无法将其解构为仅显示电子邮件或名称等。

这里是AccountScreen.js组件。在进行API调用之后,我得到了console.log(结果(,它正确地进行了日志记录,返回了一个带有电子邮件和名称的用户对象。然而,在我拥有{user.email}的地方,什么都没有显示。如果我只放{user},我会得到这个错误代码

"错误:对象作为React子对象无效(找到:具有键{result}的对象(。如果要渲染子对象的集合,请改用数组">

import React, { useState, useEffect } from 'react';
import axios from 'axios';
import Cookies from 'universal-cookie';
const cookies = new Cookies();
const token = cookies.get("TOKEN");

function AccountScreen() {
const [ user, setUser ] = useState("");

// useEffect executes once the page loads 
useEffect(() => {
// set configuration for API call
const configuration = {
method: "get",
url: "MYURL/account",
headers: {
Authorization: `Bearer ${token}`,
},
};
axios(configuration)
.then((result) => {
console.log(result); 
//assign the User to the in result to User we initialized
setUser({result});
})
.catch((error) => {
error = new Error();
});
}, []);

return(
<div className="container">
<h2>
Dashboard
</h2>
<h3>email:{user.email}</h3>
</div>
);
}
export default AccountScreen;

我对后台进行了一个API调用,这里是那里的相关代码。它成功地返回了一个带有电子邮件和名称的对象,正如我所希望的那样

// authentication endpoint
app.get("/account", auth, (request, response) => {
User.findOne({email: request.user.userEmail})
.then((user) => {
response.status(200).send({
email: user.email,
name: user.name,
})
})
.catch((error) => {
response.status(404).send({
message: "User not found",
error,
})
});
});

这里是auth组件,它在其中返回用户对象(包括用户的电子邮件(,/accountneneneba API使用该对象在DB中查找帐户。

const jwt = require('jsonwebtoken');
module.exports = async (request, response, next) => {
try {
// get the token from the authorization header
const token = await request.headers.authorization.split(" ")[1];
// check if token matches the supposed original
const decodedToken = await jwt.verify(
token,
"RANDOM-TOKEN"
);
// retrieve the user details of the logged in user 
const user = await decodedToken;
// pass the user down to the endpoints here
request.user = user;
// pass down functionality to the endpoint
next();

} catch (error) {
response.status(401).json({
error: new Error("Invalid Request!"),
});
}
}

总之,在我的帐户页面上,它应该在"旁边显示用户电子邮件;电子邮件:";,然而,我还没能弄清楚如何破坏对象以只显示那一位信息,而且目前它在"旁边的页面上什么都没有显示;电子邮件:";有一次,我使用了JSON.stringify,并能够获得要显示的信息,但它将整个对象显示为字符串,我一次只想显示一个项目。

提前感谢您的帮助!

我想通了!我需要将它作为setUser(result.data(;而不是({result}(。我以前尝试过,但当时我也在处理我的其他代码,所以我一定刚刚解决了我为自己创建的问题。

我想我明白问题的根源了。在服务器中,这是您返回的格式

{ 
email:value,
name : value
}

所以它是一个有两个属性emailname的对象。

在客户端,您使用的http客户端是axios,所以当您使用axios来挖掘服务器发送的数据时,它是通过data属性,而不是像distructuring syntax中那样通过result

因此,不要使用setUser({result});,而是使用setUser({data});,但要做到这一点,您应该像.then({data})=>{setUser({data})}一样对调用result的响应参数进行分解,因为在axios中,它是允许您访问服务器数据的属性。

这是关于data属性的文档:响应模式

最新更新