[英]Why it gets the correct data from localStorage only after refreshing the page in React
I have been unable to deal with this problem in React for a long time and I am asking for your help.很长一段时间我都无法在 React 中处理这个问题,我正在寻求您的帮助。 I will be very grateful.
我将不胜感激。 You going to be my hero?
你会成为我的英雄吗? :)) The problem is that I want to assign roles from RoleConnecton to localStorage and then render the components that are suitable for the role.
:)) 问题是我想将 RoleConnecton 中的角色分配给 localStorage,然后渲染适合该角色的组件。 However, this happens only after the page is refreshed.
但是,这仅在页面刷新后才会发生。 I don't know how to fix this without the need to refresh the page.
我不知道如何在无需刷新页面的情况下解决此问题。
App.js ->应用程序.js ->
const App = () => {
const { user, isAuthenticated } = useAuth0();
return (
isAuthenticated && (
<>
<RoleConnection />
<Admin dataProvider={jsonServerProvider('Link to database here')} i18nProvider={i18nProvider}>
{permissions =>[
localStorage.getItem("role") ==="medic"
?
<Resource name="employee" list={EmployeeList} edit={EmployeeEdit} create={EmployeeCreate} icon={WorkRounded}/>
: null,
<Resource name="hospital" list={HospitalList} edit={HospitalEdit} create={HospitalCreate} icon={LocalHospitalRounded}/>,
localStorage.getItem("role") === "doctor"
? <Resource name="order" list={OrderList} edit={OrderEdit} create={OrderCreate} icon={PersonRounded}/>
: null,
localStorage.getItem("role") === "medic"
? <Resource name="order" list={OrderList} edit={OrderEditMedic} create={OrderCreateMedic} icon={LocalHospitalRounded}/>
: null,
<Resource name="patient" list={PatientList} edit={PatientEdit} create={PatientCreate} icon={PersonRounded}/>,
]}
</Admin>
<LogoutButton />
</>
)
);
};
export default App;
RoleConnection ->角色连接->
import React from 'react';
import { useAuth0 } from "@auth0/auth0-react";
const RoleConnection = () => {
const { user, isAuthenticated } = useAuth0();
const auth_id = 'Auth ID HERE';
fetch(`Link to Auth0/api/v2/users/${user.sub}/roles`, {
method: 'get',
headers: new Headers({
'Authorization': `Bearer ${auth_id}`
})
})
.then(response => response.json())
.then(data => {
let role = data[0].name;
localStorage.setItem('role', role);
});
After Editing - Thanks to Someone Special编辑后 - 感谢特别的人
App.js应用程序.js
const App = () => {
const { user, isAuthenticated } = useAuth0();
const [ role, setRole ] = useState(null)
useEffect(() => {
if(user) auth()
},[user])
const auth = () => {
fetch(`Link to Auth0/api/v2/users/${user?.sub}/roles`, {
method: 'get',
headers: new Headers({
'Authorization': `Bearer ${auth_id}`
})
})
.then(response => response.json())
.then(data => {
console.log("Data: " + data[0].name)
setRole(data[0].name)
});
}
console.log("Check Role: "+ role);
return (
isAuthenticated && (
<>
<Admin dataProvider={jsonServerProvider('Link to database here')} i18nProvider={i18nProvider}>
{permissions =>[
console.log("Role "+ role),
role =="medic"
?
<Resource name="employee" list={EmployeeList} edit={EmployeeEdit} create={EmployeeCreate} icon={WorkRounded}/>
: null,
<Resource name="hospital" list={HospitalList} edit={HospitalEdit} create={HospitalCreate} icon={LocalHospitalRounded}/>,
role === "doctor"
? <Resource name="order" list={OrderList} edit={OrderEdit} create={OrderCreate} icon={PersonRounded}/>
: null,
role === "medic"
? <Resource name="order" list={OrderList} edit={OrderEditMedic} create={OrderCreateMedic} icon={LocalHospitalRounded}/>
: null,
<Resource name="patient" list={PatientList} edit={PatientEdit} create={PatientCreate} icon={PersonRounded}/>,
]}
</Admin>
<LogoutButton />
</>
)
);
};
export default App;
At this point, there is no error, but the relevant sections are not displayed.至此,没有报错,只是相关部分没有显示出来。 From the login console, you can deduce that the null value is entered into the role.
从登录控制台可以推断出null值被输入到角色中。 However, when I check the data, there is actually a role that should be assigned.
但是,当我检查数据时,实际上应该分配一个角色。 Does anyone know how to solve this problem?
有谁知道如何解决这个问题?
What you doing is anti pattern.你做的是反模式。 u should move the entire login into App itself.
您应该将整个登录名移至应用程序本身。
App.js应用程序.js
const App = () => {
const { user, isAuthenticated } = useAuth0();
const [ role, setRole ] = useState(null)
useEffect(() => {
if (user) auth()
},[user])
const auth = () => {
fetch(`Link to Auth0/api/v2/users/${user?.sub}/roles`, {
method: 'get',
headers: new Headers({
'Authorization': `Bearer ${auth_id}`
})
})
.then(response => response.json())
.then(data => {
setRole(data[0].name)
});
}
return (
isAuthenticated && (
<>
<Admin dataProvider={jsonServerProvider('Link to database here')} i18nProvider={i18nProvider}>
{permissions =>[
role ==="medic"
?
<Resource name="employee" list={EmployeeList} edit={EmployeeEdit} create={EmployeeCreate} icon={WorkRounded}/>
: null,
<Resource name="hospital" list={HospitalList} edit={HospitalEdit} create={HospitalCreate} icon={LocalHospitalRounded}/>,
role === "doctor"
? <Resource name="order" list={OrderList} edit={OrderEdit} create={OrderCreate} icon={PersonRounded}/>
: null,
role === "medic"
? <Resource name="order" list={OrderList} edit={OrderEditMedic} create={OrderCreateMedic} icon={LocalHospitalRounded}/>
: null,
<Resource name="patient" list={PatientList} edit={PatientEdit} create={PatientCreate} icon={PersonRounded}/>,
]}
</Admin>
<LogoutButton />
</>
)
);
};
export default App;
That's actually a misuse of Components.这实际上是对组件的滥用。 This
RoleConnection
- does it return anything (any JSX)?这个
RoleConnection
- 它是否返回任何东西(任何 JSX)? If not, it shouldn't be rendered.如果不是,则不应渲染。
You could just place its function (the one that gets a role
and sets it to localStorage
) somewhere (as @FelixKling said, App
's useEffect()
is probably the best) and just render conditionally.您可以将其 function (获得
role
并将其设置为localStorage
的那个)放在某个地方(正如@FelixKling 所说, App
的useEffect()
可能是最好的),然后有条件地渲染。
Last, but not least, that's why you shouldn't rely on localStorage
solely.最后但同样重要的是,这就是为什么您不应该仅仅依赖
localStorage
。 What I'd do is to set this role
as a React variable also (eg. in state).我要做的是将这个
role
也设置为 React 变量(例如,在状态中)。 That way you could write a useEffect()
with this role
as a dependency.这样你就可以编写一个
useEffect()
将此role
作为依赖项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.