简体   繁体   English

无法将数据存储在本地存储中并在 React 的页面刷新时使用它

[英]Not able to store data in local storage and use it on page refresh in React

I'am using Firebase version 8.10.0 as the DB in my app, and I succeeded to show the data in my page.我在我的应用程序中使用 Firebase 版本8.10.0作为数据库,并成功在我的页面中显示数据。 So generally Firebase consumes useEffect to show the data.所以一般 Firebase 使用useEffect来显示数据。

Also I succeeded to drag and drop the positions of table that contains firebase data.我还成功拖放了包含 firebase 数据的表的位置。 By my pain is to store the drag and drop positions in state and that state should be stored in localStorage .我的痛苦是将拖放位置存储在 state 中,并且 state 应该存储在localStorage中。

My destination is to create a separate state that to be stored dragged items in localStorage .我的目标是创建一个单独的 state ,将拖动的项目存储在localStorage中。 I tried this code but no result:我试过这段代码但没有结果:

import React, { useState, useEffect, useRef } from "react";
import "./BootTable.css";
import "./Appa.css";
import "../node_modules/bootstrap/dist/css/bootstrap.min.css";
import firebaseDB from "./firebased";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";

function App() {
  const dragItem = useRef();
  const dragOverItem = useRef();
  const [getData, setGetData] = useState({});

  //To Show the data    
  useEffect(() => {
    firebaseDB.child("register").on("value", (details) => {
      console.log(details.val());
      setGetData(details.val());
    });
  }, []);
 
  //To Store the dragged data into localStorage
  useEffect(() => {
    const data = window.localStorage.getItem("MY_DRAGGED_DATA");
    if (data !== null) setGetData(JSON.parse(data));
  }, []);
   
 //To set the item to localstorage

  useEffect(() => {
    console.log("show data", getData);

    window.localStorage.setItem("MY_DRAGGED_DATA", JSON.stringify(getData));
  }, [getData]);

  const deleteHandler = (key) => {
    firebaseDB.child(`register/${key}`).remove(() =>
      toast.error("Deleted!", {
        position: "top-right",
      })
    );
  };

  const dragStart = (e, position) => {
    dragItem.current = position;
    console.log(e.target.innerHTML);
  };

  const dragEnter = (e, position) => {
    dragOverItem.current = position;
    console.log(e.target.innerHTML);
  };
  const drop = (e) => {
    const copyListItems = [...Object.values(getData)];
    const dragItemContent = copyListItems[dragItem.current];
    copyListItems.splice(dragItem.current, 1);
    copyListItems.splice(dragOverItem.current, 0, dragItemContent);
    dragItem.current = null;
    dragOverItem.current = null;
    setGetData(copyListItems);
  };

  return (
    <div className="full_Container">
      <center>
        <h6 className="h6_heading">Winners</h6>
      </center>

      <table className="table " id="data-table">
        <thead className="table-hero">
          <tr>
            <th scope="col">S.no</th>
            <th className="put_pointer" scope="col">
              Name ▲▼
            </th>
            <th className="" scope="col">
              Company Name
            </th>
            <th className="put_pointer" scope="col">
              LTP
            </th>
            <th className="put_pointer" scope="col">
              %
            </th>
            <th className="put_pointer" scope="col">
              52 W.H
            </th>
            <th className="" scope="col">
              52 W.L
            </th>
            <th scope="col">M.B</th>
            <th className="" scope="col">
              Mkt.Cap
            </th>
            <th className="" scope="col">
              Volume
            </th>
            <th className="" scope="col">
              Zauba
            </th>
            <th className="" scope="col">
              M.C
            </th>
            <th className="" scope="col">
              N
            </th>
            <th className="" scope="col">
              C.I
            </th>
            <th className="" scope="col">
              Del
            </th>
          </tr>
        </thead>
        <tbody>
          {getData &&
            Object.keys(getData).map((key, index) => (
              <tr
                style={{ cursor: "move" }}
                onDragStart={(e) => dragStart(e, index)}
                onDragEnter={(e) => dragEnter(e, index)}
                onDragEnd={drop}
                key={index}
                draggablekey={index}
                draggable
              >
                <td>{index + 1}</td>

                <td>
                  <a
                    target="_blank"
                    style={{ color: "#212529" }}
                    href={getData[key].url}
                  >
                    {getData[key].name}
                  </a>
                </td>
                <td>
                  {" "}
                  <a
                    target="_blank"
                    style={{ color: "#212529" }}
                    href={getData[key].tradingview}
                  >
                    {getData[key].companyname}
                  </a>
                </td>
                <td>{getData[key].ltp}</td>
                <td>{getData[key].percent}</td>
                <td className="wk_low">{getData[key].weekhigh}</td>
                <td className="wk_low">{getData[key].weeklow}</td>
                <td className="wk_high">
                  {(getData[key].weekhigh / getData[key].weeklow).toFixed(2)}
                </td>
                <td>{getData[key].mcap}</td>
                <td>{getData[key].volume}</td>

                <td>
                  <a target="_blank" href={getData[key].zauba}>
                    <button
                      style={{
                        color: "#D39B16",
                        padding: "3px",
                        fontWeight: 1000,
                      }}
                      className="btn   btn-sm"
                    >
                      Z
                    </button>
                  </a>
                </td>
                <td>
                  <a target="_blank" href={getData[key].mc}>
                    <button
                      style={{
                        color: "#FF60AB",
                        padding: "3px",
                        fontWeight: 1000,
                      }}
                      className="btn  btn-sm"
                    >
                      M
                    </button>
                  </a>
                </td>
                <td>
                  <a target="_blank" href={getData[key].mc}>
                    <button
                      style={{
                        color: "#19be7b",
                        padding: "3px",
                        fontWeight: 1000,
                      }}
                      className="btn  btn-sm"
                    >
                      N
                    </button>
                  </a>
                </td>
                <td>
                  <a target="_blank" href={getData[key].ci}>
                    <button
                      style={{
                        color: "#19be7b",
                        padding: "3px",
                        fontWeight: 1000,
                      }}
                      className="btn  btn-sm"
                    >
                      C.I
                    </button>
                  </a>
                </td>
                <td>
                  <button
                    style={{ color: "#fff", padding: "3px", fontWeight: 1000 }}
                    className="btn  btn-sm btn-danger"
                    onClick={() => deleteHandler(key)}
                  >
                    Del
                  </button>
                </td>
                {/* {`https://roohhi.com/convert?name=${(filteredPerson.company.toLowerCase().replace(".",""))}` } */}
              </tr>

              //     <tr>{index}</tr>
              // <tr><a>{getData[key].url}{getData[key].companyname}</a></tr>
            ))}
        </tbody>
      </table>
      <ToastContainer theme="colored" />
    </div>
  );
}

export default App;

To have what you want you should first change how you are setting your initial state so that you pick what's in the localStorage if there is any and otherwise set it to null :要获得您想要的内容,您应该首先更改设置初始 state 的方式,以便您选择localStorage中的内容(如果有),否则将其设置为null

const [getData, setGetData] = useState(
  localStorage.getItem("MY_DRAGGED_DATA")
    ? JSON.parse(localStorage.getItem("MY_DRAGGED_DATA"))
    : null
);

And make sure you only use the data from Firebase if the initial data is null (I used null to have a falsy value) and that it's the first render (with loadRef ), like so:如果初始数据是null (我使用null来获得虚假值),请确保只使用 Firebase 中的数据,并且它是第一个渲染(使用loadRef

const loadRef = useRef(true);
useEffect(() => {
  firebaseDB.child("register").on("value", (details) => {
    if (getData && loadRef.current){
      loadRef.current = false;
      return
    }
    console.log(details.val());
    setGetData(details.val());
  });
}, []); // the linter might ask you to add getData in the dependency array but don't, and you will be fine.

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

相关问题 React 站点刷新时出现 404 页面 - 404 page on React site refresh AWS Sagemaker 在线特征存储数据存储 - AWS Sagemaker online feature store data storage 将本地机器上的数据导入谷歌云存储 - Import the data from the local machine to the Google cloud Storage React Firebase - 用户在每次页面刷新后注销 - React Firebase - User is logged out after every page refresh 如何将本地存储(活动存储)迁移到谷歌云存储 - How to migrate local storage (active storage) to google cloud storage 如何将 AWS 弹性负载均衡器与 React HTML5 页面一起使用 - How to use an AWS elastic load balancer with React HTML5 page Flutter Firestore 问题:无法在 Cloud Firestore 数据库中存储注册表单数据,而是存储硬编码数据 - Flutter Firestore Issue: Not able to store Sign Up form data in Cloud Firestore DB, instead hard coded data is getting stored neo4j 使用 Load CSV 从 Google Cloud Storage 读取数据 - neo4j use Load CSV to read data from Google Cloud Storage Xamarin iOS 应用无法上传到应用商店 - Xamarin iOS app not able to upload to app store 如何将孩子的孩子与本地存储中的数据匹配(Firebase 实时数据库) - How to Match Child of a child with data from local storage (Firebase Realtime Database)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM