数据在 reactjs 上显示为未定义
Data is displayed as undefined on reactjs
我有使用 jwt 的登录服务。登录后,用户将被重定向到个人资料页面。我调用了从数据库中获取数据的服务,该服务运行良好。我可以在控制台上看到所有日志,但是当我 return html 部分中的名称时,我看不到该名称。它被写成“未定义”。
const currentUser = AuthService.user();
let token = localStorage.getItem('User');
let name;
authenticationService.findUser(jwt_decode(token)["sub"]).then (response => response.json())
.then(response=> {
name = response.name;
console.log(name);
console.log(data);
});
return (
<div>
<h1>{name}</h1>
</div>
);
{name}
in h1
in your return
is not defined.
我认为问题在于您在 fetch
函数中分配了 name=response.name
。如果您使用 class 组件,您应该在此处调用 setState
,如果您使用钩子,则应在此处调用 setName
,例如 [name,setName] = useState('')
.
let [name, setName] = useState("");
useEffect(() => {
authenticationService
.findUser(jwt_decode(token)["sub"])
.then((response) => response.json())
.then((response) => {
setName(response.name);
console.log(name);
});
}, []);
我有使用 jwt 的登录服务。登录后,用户将被重定向到个人资料页面。我调用了从数据库中获取数据的服务,该服务运行良好。我可以在控制台上看到所有日志,但是当我 return html 部分中的名称时,我看不到该名称。它被写成“未定义”。
const currentUser = AuthService.user();
let token = localStorage.getItem('User');
let name;
authenticationService.findUser(jwt_decode(token)["sub"]).then (response => response.json())
.then(response=> {
name = response.name;
console.log(name);
console.log(data);
});
return (
<div>
<h1>{name}</h1>
</div>
);
{name}
in h1
in your return
is not defined.
我认为问题在于您在 fetch
函数中分配了 name=response.name
。如果您使用 class 组件,您应该在此处调用 setState
,如果您使用钩子,则应在此处调用 setName
,例如 [name,setName] = useState('')
.
let [name, setName] = useState("");
useEffect(() => {
authenticationService
.findUser(jwt_decode(token)["sub"])
.then((response) => response.json())
.then((response) => {
setName(response.name);
console.log(name);
});
}, []);