简体   繁体   English

刷新页面时 Redux Store 设置为 null

[英]Redux Store set to null when refresh the page

Index.js索引.js

Redux Store Redux 商店

This is Redux store file where I am setting the details of the authenticated user by dispatching an action.这是 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登录.js

This is My Login Page.这是我的登录页面。 When user successfully logged in then I am dispatching an action to update the state in redux store.当用户成功登录时,我正在调度一个操作来更新 redux 存储中的状态。 In this I am dispatching an action to set the authenticated user details in redux store.在此,我正在调度一个操作来在 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配置文件.js

This is authenticated user profile page.这是经过身份验证的用户个人资料页面。 Here I am displaying the name of authenticated user by fetching data from redux store.在这里,我通过从 redux 存储中获取数据来显示经过身份验证的用户名称 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;

From here's the main problem starts.从这里是主要问题开始。 When I refresh the page it is showing error Cannot read property 'name' of null .当我刷新页面时,它显示错误无法读取 null 的属性 'name' When I search about this error then I get to know that the redux store set to default value when the page refresh.当我搜索此错误时,我知道页面刷新时 redux 存储设置为默认值。 And then i found that redux-persist will help us to store data to local storage.然后我发现 redux-persist 将帮助我们将数据存储到本地存储。 But know I don't understand how to apply this redux-persist npm package.但是知道我不明白如何应用这个 redux-persist npm 包。 Please help me.?请帮我。? And Please tell me all these assumptions are right or not.?请告诉我所有这些假设是否正确。?

Redux data will be set to initial state that is 100% true, You can make use of any browser storage as per requirement(localStorage/sessionStorage/cookies).. Redux 数据将设置为 100% 真实的初始状态,您可以根据需要使用任何浏览器存储(localStorage/sessionStorage/cookies)。

I will share you example for storing full redux store and retrieving when browser is refresh(ideally not recommended), You can save the only that data which is required on browser refresh.我将与您分享用于存储完整的 redux 存储并在浏览器刷新时检索的示例(理想情况下不推荐),您可以保存浏览器刷新所需的唯一数据。

This method will be called on evert store update此方法将在 evert 商店更新时调用

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

When page is refresh check weather we have anything in localStorage当页面刷新检查天气时,我们在 localStorage 中有任何内容

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

If we have we can pass it at the time of creating store如果我们有我们可以在创建商店时传递它

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

Important Note: Ideally not recommended to store full store data in localStorage...重要提示:理想情况下,不建议将完整存储数据存储在 localStorage 中...

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

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