简体   繁体   English

为什么只有在 React 中刷新页面后才能从 localStorage 获取正确的数据

[英]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 所说, AppuseEffect()可能是最好的),然后有条件地渲染。

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.

相关问题 刷新页面后,如何确保从 localStorage 显示正确的数据? - How can I make sure the right data gets displayed from localStorage after refreshing the page? localStorage中的JWT仅在刷新页面后才能工作 - JWT in localStorage only works after refreshing the page LocalStorage JS - 刷新页面后存储数据以保持持久性是否安全? - LocalStorage JS - is it safe to store data to keep persistent after refreshing the page? 使用 firebase.on() 刷新页面后,仅从 firesbase 获取最后一个数据 - Only last data is fetched from firesbase after refreshing the page with firebase .on() React Router 仅在刷新页面后才起作用 - React Router works only after refreshing the page 为什么刷新页面后我的项目被更改了? - Why after refreshing the page my items gets changed? 刷新页面后 localStorage 值设置为 undefined - localStorage values are set to undefined after refreshing the page 刷新页面后LocalStorage不显示todolist数组 - LocalStorage not displaying array of todolist after refreshing page 使用 Javascript,我试图将数据保存在浏览器的 SessionStorage 和 localStorage 中,但刷新页面后数据丢失 - Using Javascript, I am trying to persist the data in SessionStorage and localStorage of browser but after refreshing the page the data is lost 反应,页面刷新后使用useEffect丢失localStorage中保存的数据 - React, losing saved data in localStorage with useEffect after page refresh
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM