简体   繁体   English

在反应中使用usestate localstorage的maltiple值如何?

[英]How maltiple value using usestate localstorage in react?

I want to work using maltiple values in use state and crud in local storage use state like const [Data,setData]=[[{ name:'luis', pass:'1234', //....... }] ]我想在使用状态中使用 maltiple 值,在本地存储使用状态中使用 crud,例如 const [Data,setData]=[[{ name:'luis', pass:'1234', //....... } ] ]

And it updates with the form
<input>

// ....... // .......

if value true  Display  take look at this example I try but I cannot do how to solve it

import './App.css';导入'./App.css'; import React, { useState,useEffect } from 'react';导入反应,{ useState,useEffect } from 'react';

function App() {
  const [User, setUser] = useState([
    {
      Name:'',
      Pass:'',
      Email:'',
    }
  ]);

 
  const [storedUser,setstoredUser]=useState([])

  
  const handle = () => {

     localStorage.setItem(JSON.stringfy(...User))
    
     setstoredUser(...User);

  };
  const remove = () => {
     localStorage.removeItem();

  };
  return (
    <div className="App">
         <h1>Name of the user:</h1>
         <input
            placeholder="Name"
            name='Name'
            value={User.Name}
            onChange={(e) => setUser({...User,[e.target.name]:[e.target.value]})}
         />
         <h1>Password of the user:</h1>
         <input
            type="password"
            name="Pass"
            placeholder="Password"
            value={User.Pass}
            onChange={(e) => setUser({...User,[e.target.name]:[e.target.value]})}
         />
           <h1>Email of the user:</h1>
          <input
            type="mail"
            name="Email"
            placeholder="Email"
            value={User.Email}
            onChange={(e) => setUser({...User,[e.target.name]:[e.target.value]})}
         />
         <div>
            <button onClick={handle}>Done</button>
         </div>
         {storedUser.Name && (
            <div>
               Name: <p>{localStorage.getItem('Name')}</p>
            </div>
         )}
         {storedUser.Pass && (
            <div>
               Password: <p>{localStorage.getItem('Pass')}</p>
            </div>
         )}
          {storedUser.Email && (
            <div>
               Password: <p>{localStorage.getItem('Email')}</p>
            </div>
         )}
         <div>
            <button onClick={remove}>Remove</button>
         </div>
      </div>
   ); 
}

export default App;

Here I try how to do this formate I try to all data in state and stringify set this local storage.在这里我尝试如何做这个格式我尝试将所有数据状态和字符串化设置这个本地存储。 then remove and display I think explaine on detail然后删除并显示我认为详细解释

You're missing the key你错过了钥匙

localStorage.setItem("User",JSON.stringfy(...User))

If you want each key.如果你想要每个键。 Loop over they keys and values and set them.循环遍历它们的键和值并设置它们。 As stated by another user, your UserState is an array where it should just be an object正如另一位用户所说,您的 UserState 是一个数组,它应该只是一个对象

Object.entries(User).forEach(([key,value])=>{
      localStorage.setItem(key,value)
    })

Since User already is an array of user objects I wouldn't spread them in your handle function.由于User已经是一个用户对象数组,我不会在您的handle函数中传播它们。 You also need to set a key if you're saving in localStorage .如果您保存在localStorage中,您还需要设置一个key This is how to save your list of users under "users" :这是如何将您的用户列表保存在"users"下:

const handle = () => {
  localStorage.setItem("users", JSON.stringfy(User));
  setstoredUser(User);
};

Now when retrieving users from the localStorage you can make use of JSON.parse like this:现在,当从localStorage检索用户时,您可以像这样使用JSON.parse

users = JSON.parse(localStorage.getItem("users") || "[]");

And for deletion you would need the key "users" here as well:对于删除,您还需要这里的关键"users"

localStorage.removeItem("users");

You are doing a few things incorrectly here:你在这里做错了一些事情:

  • you are not providing a key for local storage您没有为本地存储提供密钥
  • you don't need to spread objects directly inside setState您不需要直接在 setState 内传播对象
  • use the removeItem method to clear the user from localStorage使用 removeItem 方法从 localStorage 中清除用户
  • you are setting the user as an array to state not an object, this is unnecessary in the example you have您将用户设置为数组以声明不是对象,这在您的示例中是不必要的

If the goal is to persist a single user between sessions via local storage.如果目标是通过本地存储在会话之间保持单个用户。 Then all you need to do is save the user to local storage when the form is submitted.然后,您需要做的就是在提交表单时将用户保存到本地存储。 Then, when the component loads, check local storage for user data.然后,当组件加载时,检查本地存储以获取用户数据。

import { useEffect, useState } from 'react'

function App() {
  const [User, setUser] = useState({
    Name: '',
    Pass: '',
    Email: '',
  })

  const handle = () => {
    const nextUser = JSON.stringify(User)
    localStorage.setItem('user', nextUser)
  }
  const remove = () => {
    localStorage.removeItem('user')
  }

  useEffect(() => {
    const storedUser = localStorage.getItem('user')
    if (storedUser) {
      setUser(JSON.parse(storedUser))
    }
  }, [])
  return (
    <div className="App">
      <h1>Name of the user:</h1>
      <input
        placeholder="Name"
        name="Name"
        value={User.Name}
        onChange={(e) => setUser({ ...User, [e.target.name]: e.target.value })}
      />
      <h1>Password of the user:</h1>
      <input
        type="password"
        name="Pass"
        placeholder="Password"
        value={User.Pass}
        onChange={(e) => setUser({ ...User, [e.target.name]: e.target.value })}
      />
      <h1>Email of the user:</h1>
      <input
        type="mail"
        name="Email"
        placeholder="Email"
        value={User.Email}
        onChange={(e) => setUser({ ...User, [e.target.name]: e.target.value })}
      />
      <div>
        <button onClick={handle}>Done</button>
      </div>

      {User.Name && (
        <div>
          Name: <p>{User.Name}</p>
        </div>
      )}
      {User.Pass && (
        <div>
          Password: <p>{User.Pass}</p>
        </div>
      )}
      {User.Email && (
        <div>
          Password: <p>{User.Email}</p>
        </div>
      )}
      <div>
        <button onClick={remove}>Remove</button>
      </div>
    </div>
  )
}

export default App

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

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