【问题标题】:Not getting localstorage data without page refresh in react project在反应项目中没有页面刷新就无法获取本地存储数据
【发布时间】:2022-10-25 14:13:36
【问题描述】:

当我回到注册页面时我需要刷新页面,注册后我需要刷新以显示登录页面,当登录页面出现时我需要再次刷新以获取本地存储数据。然后登录工作。再次在主页显示数据。可能是从本地存储发送或获取数据不正常,但不知道解决方案。

注册.jsx

import React, { useState } from 'react';
import { useDispatch } from 'react-redux';
import { Link,useNavigate } from 'react-router-dom';
const Regiter = () => {
    const[username,setUsername]=useState('')
    const[email,setEmail]=useState('')
    const[location,setLocation]=useState('')
    const[password,setPassword]=useState("")
    const[confirmPassword,setConfirmPassword]=useState("")
   const dispatch=useDispatch();
   const navigate=useNavigate()
    const register=(e)=>{
        if(username===""){
            alert("Provide Username")
        }else if(email==="" && !email.includes("@")){
            alert("Invalid Email")
        }else if(location===""){
            alert("Provide Location")
        }else if(password.length<5){
            alert("Password must be 5+ character")
        }
       if(username && email && location && password && confirmPassword ){
        dispatch({
            type:"REGISTER",
            payload:{
                id:(new Date()).getTime(),
                username,email,password,location
            }
        });
        localStorage.setItem("user",JSON.stringify({
            users:[
                username,
                email,
                password,
                location
            ]
        }))
        alert("Registered")
        navigate("/login", { replace: true });
       }
    }


 return (
            <form className=''>
                <div className="bg-grey-lighter min-h-screen flex flex-col drop-shadow-lg">
                    <div className="container max-w-sm mx-auto flex-1 flex flex-col items-center justify-center px-2">
                        <div className="bg-white px-6 py-8 rounded shadow-md text-black w-full">
                            <h1 className="mb-8 text-3xl text-center">Regsiter</h1>
                            <input 
                                type="text"
                                className="block border border-grey-light w-full p-3 rounded mb-4"
                                autoComplete='usename'
                                name='username'
                                placeholder="User Name"
                                onChange={(e)=>setUsername(e.target.value)} />

                            <input 
                                type="text"
                                className="block border border-grey-light w-full p-3 rounded mb-4"
                                autoComplete='current-email'
                                name='email'
                                placeholder="Email" 
                                onChange={(e)=>setEmail(e.target.value)}/>

                            <input 
                                type="password"
                                className="block border border-grey-light w-full p-3 rounded mb-4"
                                autoComplete='new-password'
                                name='password'
                                placeholder="Password"
                                onChange={(e)=>setPassword(e.target.value)}/>
                            <input 
                                type="password"
                                className="block border border-grey-light w-full p-3 rounded mb-4"
                                placeholder="Confirm Password"
                                name='confirm_pass'
                                onChange={(e)=>setConfirmPassword(e.target.value)}/>
                                {password!==confirmPassword&&<small key={email+password} className="text-red-700">Not Matched</small>}
                            <input 
                                type="text"
                                className="block border border-grey-light w-full p-3 rounded mb-4"
                                placeholder="Location"
                                name='location'
                                onChange={(e)=>setLocation(e.target.value)}/>

                            <input
                                type="button"
                                className="w-full text-center py-3 rounded bg-green-600 text-white hover:bg-green-dark focus:outline-none my-1"
                                value="Submit"
                                onClick={register}
                            />
                        </div>

                        <div className="text-grey-dark mt-6">
                            Already have an account? 
                            <Link className="no-underline border-b border-blue text-blue-800 px-2" to="/login">
                                Log in
                            </Link>.
                        </div>
                </div>
               </div>
            </form>
    )
}

导出默认注册

减速器.jsx

import { legacy_createStore as createStore} from 'redux'

const initialState=JSON.parse(localStorage.getItem("user"))||{
    users:[]
}
console.log(initialState);
const reducer=(state=initialState,action)=>{
    switch(action.type){

        case "REGISTER":
            return{
                ...state,
                users:[...state.users,action.payload]
           
    }
    case "LOGIN":
            return{
                ...state,
                users:action.payload
           
    }
    case "LOGOUT":
            return{
                users:null
           
    }
    default:return state;
}
}
export default createStore(reducer)

【问题讨论】:

  • 由于 reducer 不是组件,因此您应该重命名 reducer 文件。从 reducer.jsx 到 reducer.js
  • 做了,但没有工作...
  • 记录初始状态时会得到什么?
  • 用户数据数组...

标签: reactjs redux local-storage


【解决方案1】:

使用来自react-reduxuseSelector 钩子在存储状态更改时更新您的组件。

https://react-redux.js.org/api/hooks#useselector

为您提供解决方案:

注册用户后,导航到呈现注册用户的“/”,您可以将其实现为

const Home = () => {
  // Return the state corresponding to what you want to display. 
  // In this case, I am considering user as my state stored in the redux-store. 
  const user => useSelector(state => state.user)

  return user ? <div>{user.name}</div> : <div>No user found</div>
}

跟进点:

  1. 尝试使用@reduxjs/toolkit 代替redux,因为它是这些天的首选。
  2. 在注册后存储到 localstorage 时,您将用户设置为所有用户详细信息的数组,但是分派了一个有效负载对象,该对象将一个元素附加到用户详细信息数组中。不确定这里发生了什么。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-29
    • 2022-07-12
    • 2021-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多