react函数组件中如何存储一组数据到localStorage中
时间: 2024-03-13 17:46:54 浏览: 121
在React函数组件中存储一组数据到localStorage中,可以按照以下步骤进行操作:
1. 使用 `useState` hook 定义一个数组来存储数据,例如:
```javascript
const [data, setData] = useState([]);
```
2. 在组件挂载时,从localStorage中获取之前存储的数据,如果有则更新state:
```javascript
useEffect(() => {
const storedData = localStorage.getItem('data');
if (storedData) {
setData(JSON.parse(storedData));
}
}, []);
```
3. 当数据更新时,将数据存储到localStorage中:
```javascript
useEffect(() => {
localStorage.setItem('data', JSON.stringify(data));
}, [data]);
```
完整代码示例:
```javascript
import React, { useState, useEffect } from 'react';
const MyComponent = () => {
const [data, setData] = useState([]);
useEffect(() => {
const storedData = localStorage.getItem('data');
if (storedData) {
setData(JSON.parse(storedData));
}
}, []);
useEffect(() => {
localStorage.setItem('data', JSON.stringify(data));
}, [data]);
const handleAdd = (item) => {
const newData = [...data, item];
setData(newData);
}
return (
<div>
<button onClick={() => handleAdd('new item')}>Add</button>
<ul>
{data.map((item, index) => <li key={index}>{item}</li>)}
</ul>
</div>
);
}
```
阅读全文