NodeJS 刷新页面时Redux Store设置为null

eivnm1vs  于 2023-06-05  发布在  Node.js
关注(0)|答案(2)|浏览(209)

index.js
Redux商店

这是Redux存储文件,我通过调度操作来设置已验证用户的详细信息。

import { createStore } from "redux";
function reducerFunction(state = {authenticatedUser: null}, action){                      
    console.log("It is working");
    if(action.type === "USER_LOGIN"){
        console.log(action.payload);
        return {authenticatedUser: action.payload}
    }
    return {authenticatedUser: null}
}
export const store = createStore(reducerFunction);

Login.js

这是我的登录页面。当用户成功登录后,我将调度一个操作来更新redux存储中的状态。在这里,我调度了一个操作来设置redux商店中的已验证用户的详细信息。

import { useState } from "react";
import { Link, useHistory } from "react-router-dom";
import { useSelector, useDispatch } from "react-redux";
const Login = () => {
  const dispatch = useDispatch();
  const history = useHistory();
  const [email, setemail] = useState("");
  const [password, setpassword] = useState("");

  const emailChangeHandler = (e) => {
    setemail(e.target.value);
  };

  const passwordChangeHandler = (e) => {
    setpassword(e.target.value);
  };

  const submitHandler = async (e) => {
    e.preventDefault();
    const userData = {
      email,
      password,
    };
    try {
      const response = await fetch("/login", {
        method: "POST",
        body: JSON.stringify(userData),
        headers: {
          "Content-Type": "application/json",
        },
      });
      const data = await response.json();
      console.log(data);
      localStorage.setItem("jwt", data.token);
      localStorage.setItem("user",
        JSON.stringify({
          name: data.user.name,
          email: data.user.email,
          _id: data.user._id,
        })
      );
      dispatch({ type: "USER_LOGIN", payload: data.user });        //Here I am dispatching an action to set the authenticated user details in redux store.
      history.push("/");
    } catch (e) {
      console.log(e);
    }
    setemail("");
    setpassword("");
  };
  return (
    <div className="mycard">
      <div className="card auth-card input-field">
        <h2>Instagram</h2>
        <form onSubmit={submitHandler}>
          <input type="text" placeholder="email" onChange={emailChangeHandler} value={email} />
          <input type="text" placeholder="password" onChange={passwordChangeHandler} value={password} />
          <button className="btn waves-effect waves-light" type="submit" name="action" > Submit </button>
        </form>
        <p>
          <Link to="/signup">Don't have an account?</Link>
        </p>
      </div>
    </div>
  );
};
export default Login;

Profile.js

这是经过身份验证的用户配置文件页。这里我通过从redux store获取数据来显示认证用户名authenticatedUser.name

import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import classes from "./Profile.module.css";
const Profile = () => {
    const [images, setImages] = useState([]);
    const [image, setImage] = useState("");
    const [url, setUrl] = useState("");
    const dispatch = useDispatch();
    const authenticatedUser = useSelector(state => state.authenticatedUser);    //Here I am fetching authenticated user.

    useEffect(async() => {
        const response = await fetch("/myPost", {
            method: "GET",
            headers: {
                "Authorization": "Bearer " + localStorage.getItem("jwt"),
                "Content-Type": "application/json"
            }
        })
        const data = await response.json();
        console.log(data);
        setImages(data);
    }, [])

    return (
        <div>
            <div>
                <div>
                    <img className={classes.profile_image} src="https://images.unsplash.com/photo-1534972195531-d756b9bfa9f2?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=750&q=80"/>
                </div>
                <div >
                    <h1>{authenticatedUser.name}</h1>
                    <div>
                        <h4>80 posts</h4>
                        <h4>80 followers</h4>
                        <h4>80 following</h4>
                    </div>
                </div>
            </div>

            <div className={classes.gallery}>
                {images.map(image => {
                    return <img src={image.image}/>
                })}
            </div>
        </div>
    );
}
export default Profile;

从这里的主要问题开始。当我刷新页面时,它显示错误Cannot read property 'name' of null。当我搜索这个错误时,我知道当页面刷新时,redux商店设置为默认值。然后我发现redux-persist可以帮助我们将数据存储到本地存储。但是我知道我不明白如何应用这个redux-persist npm包。请帮帮我请告诉我所有这些假设是正确的或不。

a14dhokn

a14dhokn1#

Redux数据将被设置为100%真实的初始状态,您可以根据要求使用任何浏览器存储(localStorage/sessionStorage/cookie)。
我将分享你的例子存储完整的redux存储和检索时,浏览器刷新(理想情况下不推荐),你可以保存唯一的数据,这是需要在浏览器刷新。
此方法将在每次存储更新时调用

store.subscribe(()=>{
  // save a copy to localStorage
  localStorage.setItem('reduxState', JSON.stringify(store.getState()))
})

当页面刷新检查天气我们有任何在localStorage

const persistedState = localStorage.getItem('reduxState') 
                       ? JSON.parse(localStorage.getItem('reduxState'))
                       : {}

如果我们有,我们可以在创建商店时传递它

const store = createStore(
      reducer, 
      persistedState,
     /* any middleware... */
)

重要提示:理想情况下,不建议将完整存储数据存储在localStorage中...

mhd8tkvw

mhd8tkvw2#

如果在刷新页面时Redux存储被设置为null,则表明在页面重新加载之间状态不会持久化。默认情况下,Redux本身不处理状态持久化。
要在页面刷新过程中保持Redux状态,可以使用其他库或技术,如浏览器本地存储或会话存储。下面是一个如何使用本地存储实现状态持久化的示例:
安装redux-persist库:

npm install redux-persist

在应用程序中使用Redux Persists设置Redux商店:

import { createStore } from 'redux';
import { persistStore, persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage'; // Defaults to local storage

import rootReducer from './reducers'; // Your root reducer

const persistConfig = {
  key: 'root',
  storage,
};

const persistedReducer = persistReducer(persistConfig, rootReducer);

export const store = createStore(persistedReducer);
export const persistor = persistStore(store);

在此代码中,persistConfig指定用于持久化Redux状态的键和存储方法。persistReducer函数用持久性配置 Package 根reducer。导出存储区和持久化器以在应用程序中使用。
使用Redux-persistent中的PersistGate Package 应用组件:

import { Provider } from 'react-redux';
import { PersistGate } from 'redux-persist/integration/react';

import { store, persistor } from './store';

const App = () => {
  return (
    <Provider store={store}>
      <PersistGate loading={null} persistor={persistor}>
        {/* Your application component hierarchy */}
      </PersistGate>
    </Provider>
  );
};

export default App;

请务必查看Redux Persists文档,以获得更高级的配置选项和基于您特定需求的自定义。

相关问题