简体   繁体   English

如何在 React JS 中的页面刷新时选中持久复选框?

[英]How to get persist checkbox checked on page refresh in React JS?

I'm trying to display checkbox ( that was already checked by the user) as checked after page refresh.我试图在页面刷新后显示复选框(用户已经选中)。 I was able to save data of the selected rows in local storage (on check) and remove data on uncheck, but when I refresh the page checkbox displays as unchecked(even if local storage has the data stored in it).我能够将所选行的数据保存在本地存储中(选中时)并在取消选中时删除数据,但是当我刷新页面复选框时显示为未选中(即使本地存储中存储了数据)。

My code is我的代码是

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>
  );
}

and codeSandbox代码沙箱

As of now on box check local storage looks like this截至目前,框检查本地存储看起来像这样在此处输入图像描述

When I try to pass d.select to checked like this checked={d.select} ( so when d.select is === true box will be checked) it gets saved in localStorage as select:true but doesn't display checked on refresh.当我尝试通过 d.select 像这样检查时 check={d.select} (所以当 d.select 是 === true 框将被选中)它被保存在 localStorage 中,因为 Z99938282F040718EF42Z 已选中但不显示:刷新。 I can't figure out how to keep checked boxes still checked after page refresh.我不知道如何在页面刷新后保持选中框仍然处于选中状态。 Any help and suggestions are greatly appreciated.非常感谢任何帮助和建议。

You've got the right idea, but there are errors in your code.您的想法是正确的,但是您的代码中存在错误。

Your main problem is that when you render your component, you are mapping the values of peopleInfo , and when you're loading people to see which values have been checked before page refresh, you load them into peopleInfoValue , which you never actually reference when you're rendering your component.您的主要问题是,当您渲染组件时,您正在映射peopleInfo的值,并且当您加载人员以查看在页面刷新之前检查了哪些值时,您将它们加载到peopleInfoValue中,而您在'正在渲染你的组件。 While you are correctly setting local storage, the values in local storage never make there way to the display.当您正确设置本地存储时,本地存储中的值永远不会显示。

Use @Chris G's version it does what you want and is very nice.使用@Chris G 的版本,它可以满足您的需求并且非常好。 It's good to understand why your original code wasn't working though.很高兴了解为什么您的原始代码不起作用。

Problem问题

The list below shows the reasons why your checkbox doesn't update when the page refreshes.下面的列表显示了您的复选框在页面刷新时未更新的原因。

  • checkbox status(checked) is only handled by onChange event (the status updates only when input value is changed by the UI)复选框状态(已选中)仅由 onChange 事件处理(状态仅在 UI 更改输入值时更新)
  • useEffect only handles setting localStorage value useEffect 仅处理设置 localStorage 值

Solution解决方案

Include a method inside useEffect to do the following:在 useEffect 中包含一个方法来执行以下操作:

  • get localStorage value获取本地存储值
  • set it to the state 'peopleInfoValue'将其设置为 state 'peopleInfoValue'

I see a lot of problems here.我在这里看到了很多问题。

First: you must need to check when you initialize your state if have something in the localstorage.首先:您必须在初始化 state 时检查本地存储中是否有内容。

Second: every radio or checkbox input must have a conditional check in the property "checked":第二:每个单选框或复选框输入都必须在属性“checked”中进行条件检查:
<input name="IamCheckbox" type="checkbox" checked={user.select} />

Third: Have a lot forms to intialize this data.第三:有很多forms来初始化这个数据。 You can make a new var to pass to the useState or use the useEffect to check to you and update the state.您可以创建一个新的 var 传递给 useState 或使用 useEffect 来检查并更新 state。 If I doing this I will make the clear way as possible.如果我这样做,我会尽可能清楚地说明问题。 Because maybe you had to format the data when you initialize the state.因为也许您在初始化 state 时必须格式化数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM