cari

Rumah  >  Soal Jawab  >  teks badan

Dalam React, localstorage.getItem mengembalikan null

index.js:

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(document.getElementById('root'));
const obj = { a: "xxx", b: "yyy" }
localStorage.setItem('obj', JSON.stringify(obj));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

client.js:

let settings = JSON.parse(localStorage.getItem('obj'));
const oktaAuth = new OktaAuth({
    issuer: settings['a'],
    clientId: settings['b'],
    redirectUri: window.location.origin + '/login/callback',
    logoutUrl: window.location.origin + '/login',
    // pkce: false
});

Saya mengimport klien dalam Apl dan nampaknya localStorage harus menetapkan Item sebelum client.js dijalankan. Tetapi localStrorage.getItem('obj') saya adalah batal. Adakah sesiapa tahu mengapa?

P粉551084295P粉551084295261 hari yang lalu1665

membalas semua(1)saya akan balas

  • P粉948258958

    P粉9482589582024-04-06 11:16:28

    Gunakan useEffect()

    import React, {useEffect} from 'react';
    
    const App = () => {
    
    useEffect(() => {
    const obj = { a: "xxx", b: "yyy" }
    localStorage.setItem('obj', JSON.stringify(obj));
    },[])
    
    return (
         
    ) }

    balas
    0
  • Batalbalas