【问题标题】:useEffect not working with local storage and forEachuseEffect 不适用于本地存储和 forEach
【发布时间】:2022-12-04 00:39:50
【问题描述】:

在我的项目中,我正在使用 redux 存储,该数据将存储在本地存储中。在每次新更新时,本地存储都会更新,并且根据本地存储,我的组件将使用 forEach 方法呈现。

使用下面的代码,我从本地存储中获取数据。

const ShowMyFlashcard = () => {
let cardValueObj=[]

 useEffect(() => {

    let cardValue = localStorage.getItem("cardValue");
    if (cardValue == null) {
      cardValueObj= [];
    } else {
      cardValueObj= JSON.parse(cardValue);
    }
  });


 return (
    //  {/* SECTION TO SHOW CREATED ALL CARDS*/}

    <div className="mx-10 my-10 grid grid-cols-3 gap-4 place-content-around flex flex-wrap justify-items-center">
      {cardValueObj.forEach((element) => {
        <div className=" shadow-md bg-white p-5 h-64 w-64 m-4 mx-1.5 my-1.5">
          <div>
            <h1 className="text-center font-bold mx-1.5 my-1.5">
              {element.createGroup}
            </h1>
            <div className="text-center bg-white mx-1.5 my-1.5 h-32 w-48">
              <span>{element.groupDescription}</span>
            </div>
            <div className="flex justify-center">
              <button className="rounded-md text-red-600 border-solid border-2 bg-white border-red-700 mx-2 my-2 h-8 w-40">
                View Cards
              </button>
            </div>
          </div>
        </div>;
      })}
    </div>
  );
};

导出默认 ShowMyFlashcard;

【问题讨论】:

  • 您的代码在哪些方面没有按预期工作?请详细说明您观察到的具体问题以及您进行了哪些调试。要了解有关此社区的更多信息以及我们如何为您提供帮助,请从tour 开始并阅读How to Ask 及其链接资源。
  • 代码中的返回部分。当我对 { element.createGroup} 进行控制台操作时,我从本地存储对象获取值,但 forEach 无法使用 jsx 代码。我想要的是我需要在每次渲染或任何本地存储更新时为卡片创建一个循环。

标签: reactjs react-hooks local-storage


【解决方案1】:

.forEach() 没有返回值,因此该操作不会向页面输出任何内容。请改用.map()

此外,对您的.forEach() 的回调永远不会返回任何内容。当您使用.map() 时,还要确保回调返回您想要的值。

{cardValueObj.map((element) => (
  <div className=" shadow-md bg-white p-5 h-64 w-64 m-4 mx-1.5 my-1.5">
    the rest of your markup...
  </div>;
))}

或者使用明确的return

{cardValueObj.map((element) => {
  return (<div className=" shadow-md bg-white p-5 h-64 w-64 m-4 mx-1.5 my-1.5">
    the rest of your markup...
  </div>);
})}

【讨论】:

    【解决方案2】:

    你还没有传递任何依赖数组

    const [cardValue, setCardValue] = useState([]);
    
    useEffect(() => {
       let cardValueFromLocalStorage = localStorage.getItem("cardValue");
       if (cardValueFromLocalStorage === null) {
         setCardValue([]);
       } else {
         setCardValue(JSON.parse(cardValueFromLocalStorage));
       }}, []);
    

    请在数组中添加一些依赖项。同样使用 let 不是正确的方法尝试使用 useState Hook

    【讨论】:

    • 尝试过但对我没有用。
    • 您是否也尝试使用 useState 钩子仅依赖部分或两者?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-24
    • 2014-09-11
    • 2022-01-10
    • 2021-10-14
    • 1970-01-01
    • 2018-07-07
    相关资源
    最近更新 更多