【发布时间】:2021-06-02 14:37:14
【问题描述】:
我正在尝试在页面刷新后显示复选框(已由用户选中)。我能够将所选行的数据保存在本地存储中(选中时)并在取消选中时删除数据,但是当我刷新页面复选框时显示为未选中(即使本地存储中存储了数据)。
我的代码是
import React, { useState, useEffect } from "react";
const data = [
{
id: "1",
name: "Jane",
lastName: "Doe",
age: "25"
},
{
id: "2",
name: "James",
lastName: "Doe",
age: "40"
},
{
id: "3",
name: "Alexa",
lastName: "Doe",
age: "27"
},
{
id: "4",
name: "Jane",
lastName: "Brown",
age: "40"
}
];
export default function App() {
const [peopleInfo] = useState(
data.map((d) => {
return {
select: false,
id: d.id,
name: d.name,
lastName: d.lastName,
age: d.age
};
})
);
const [peopleInfoValue, setPeopleInfoValue] = useState(
localStorage.getItem("selectedPeople") == null
? ""
: JSON.parse(localStorage.getItem("selectedPeople"))
);
useEffect(() => {
localStorage.setItem("selectedPeople", JSON.stringify(peopleInfoValue));
}, [peopleInfoValue]);
return (
<div className="App">
<table>
<tr>
{peopleInfo?.map((d) => {
return (
<div
key={d.id}
style={{
display: "flex",
width: "150px"
}}
>
<input
style={{ margin: "20px" }}
onChange={(e) => {
// add to list
let checked = e.target.checked;
if (checked) {
setPeopleInfoValue([
...peopleInfoValue,
{
select: true,
id: d.id,
name: d.name,
lastName: d.lastName,
age: d.age
}
]);
} else {
// to remove from localstorage
setPeopleInfoValue(
peopleInfoValue.filter((people) => people.id !== d.id)
);
}
}}
// checked={d.select}
type="checkbox"
/>
<td style={{ margin: "20px" }}>{d.name}</td>
<td style={{ margin: "20px" }}>{d.lastName}</td>
<td style={{ margin: "20px" }}>{d.age}</td>
</div>
);
})}
</tr>
</table>
</div>
);
}
当我尝试像这样将 d.select 传递给检查时 checked={d.select} (所以当 d.select 为 === true 框时将被选中)它会保存在 localStorage作为 select:true 但在刷新时不显示选中。我不知道如何在页面刷新后保持选中框仍然处于选中状态。非常感谢任何帮助和建议。
【问题讨论】:
-
我修复了你的代码:codesandbox.io/s/gifted-noyce-0uq7i?file=/src/App.js(我还清理了 HTML 并将复选框更改处理程序移到 JSX 之外)
-
@Chris G,是的,这正是我想做的。谢谢!
标签: javascript reactjs checkbox local-storage