ReactJS 中的 LocalStorage
在本文中,我們將瞭解如何在 React 應用程式 中設定和檢索使用者瀏覽器 localStorage 記憶體中的資料。
LocalStorage 是一個 Web 儲存物件,用於將資料儲存在使用者的計算機本地,這意味著儲存的資料會在瀏覽器會話間儲存,且所儲存的資料沒有過期時間。
語法
// To store data
localStorage.setItem('Name', 'Rahul');
// To retrieve data
localStorage.getItem('Name');
// To clear a specific item
localStorage.removeItem('Name');
// To clear the whole data stored in localStorage
localStorage.clear();在 localStorage 中設定、檢索和移除資料
在本示例中,我們將構建一個 React 應用程式,它從使用者處獲取使用者名稱和密碼,並將它們以一個條目形式儲存在使用者計算機的 localStorage 中。
示例
App.jsx
import React, { useState } from 'react';
const App = () => {
const [name, setName] = useState('');
const [pwd, setPwd] = useState('');
const handle = () => {
localStorage.setItem('Name', name);
localStorage.setItem('Password', pwd);
};
const remove = () => {
localStorage.removeItem('Name');
localStorage.removeItem('Password');
};
return (
<div className="App">
<h1>Name of the user:</h1>
<input
placeholder="Name"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<h1>Password of the user:</h1>
<input
type="password"
placeholder="Password"
value={pwd}
onChange={(e) => setPwd(e.target.value)}
/>
<div>
<button onClick={handle}>Done</button>
</div>
{localStorage.getItem('Name') && (
<div>
Name: <p>{localStorage.getItem('Name')}</p>
</div>
)}
{localStorage.getItem('Password') && (
<div>
Password: <p>{localStorage.getItem('Password')}</p>
</div>
)}
<div>
<button onClick={remove}>Remove</button>
</div>
</div>
);
};
export default App;在上方的示例中,當點選 完成 按鈕時,執行 handle 函式,它將在使用者的 localStorage 中設定條目並顯示它們。但是,當點選 移除 按鈕時,執行 remove 函式,它將從 localStorage 中移除條目。
輸出
這將產生以下結果。

廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP