我有一个问题:当用户到达 /chat
路径时,首先应该检查他是否满足所有条件。如果没有,他将被重定向。如果他这样做了,那么他的所有数据都应该从后端保存到 localStorage
。
问题是在设置 localStorage 之前加载了 ChatComponent
。我在 localStorage .getItem(...)
中有一个 ChatComponent
,它为空,但是一旦我重新加载页面,预期值就在其中。
有没有办法只在设置了 ChatComponent
时才加载 localStorage
,这样我在 ChatComponent
中就没有空值而不必重新加载页面?
import React, { useEffect, useState } from "react";
import { useHistory } from "react-router-dom";
import { Ellipsis } from 'react-spinners-css';
import axios from "axios";
import Chatcomponent from "../components/chat/Chatcomponent";
function Chat() {
const history = useHistory();
const [isloading, setIsloading ] = useState(true);
useEffect(() => {
filledInterests()
}, []);
const filledInterests = () => {
document.body.style.cursor = "wait";
axios
.post("https://localhost:4000/profile/get", {})
.then((response) => {
if (response.data.givenname === "FILLER") {
callFirststeps();
setIsloading(false);
}
else {
if( localStorage.getItem('getName') === null ) {
loadUserData();
setIsloading(false);
}
}
})
.catch((error) => {
console.log(error);
//console.log(error.response.status);
});
document.body.style.cursor = "default";
};
const loadUserData = () => {
fillName();
fillIntersts();
// Only after the variable has been set here,
// the chat component may be loaded, so that the variables are also set.
// What I tried:
// window.location.reload();
}
const fillName = () => {
axios
.post("http://localhost:4000/profile/get",
{
"field1": "id",
"field2": "givenname",
}
)
.then((res) => {
if (res.status === 200) {
localStorage.setItem('userName', res.data.givenname);
localStorage.setItem('userEmail', res.data.email);
}
})
.catch((error) => {
console.log(error);
});
}
// eslint-disable-next-line
const callFirststeps = () => {
history.push({
pathname: "/first-steps",
state: {
},
});
};
return (
<body>
{
isloading === true &&
<Ellipsis color="#5869FF" style={{left:"50", right:"50", top:"50", bottom:"50",}}/>
}
{
isloading === false &&
<Chatcomponent></Chatcomponent>
}
</body>
);
}
export default Chat;
答案 0 :(得分:0)
不,没有其他方法可以做到这一点,您正在根据需要进行处理。您可以更改实现细节,但最终它会是相同的检查和呈现逻辑的 if 语句。