react-redux 和 redux

首先 npm install react-redux 和 npm install redux
新建store文件夹再建 index.js文件

/** @format */

import { createStore } from 'redux';
import reducer from './reducer';

const store = createStore(reducer);

export default store;

新建reducer.js 文件

export default (state = '', { type, payload }) => {
  switch (type) {
    // 登录,设置权限,和登录态
    case 'LOGIN':
      return { ...state, ...payload, isLogin: true, };
  // 登出,
    case 'LOGOUT':
      return { ...state, ...payload,isLogin: false,  };

    default:
      return state;
  }
};

在根目录引用

import { Provider, useDispatch, useSelector } from 'react-redux';
import store from './store/index';
const App = () => {
const dispatch = useDispatch();
 //登录
  const login= useCallback(async (val) => {
    try{
      const { userName, pwd } = val;
       // 调用的登录接口
      const resp = await login({
        username: userName,
        password: md5(pwd),
      });
      resp && dispatch({
        type: 'LOGIN',
        payload: resp,
      });
    }catch(e){
      message.error({ content: e.response.data.message });
    }
   
  }, [dispatch,login]);
  // 登出
  const logout = useCallback(async () => {
   // 调用的登出接口
    await fetchLogout();
    dispatch({ type: 'LOGOUT' });
  }, [dispatch, fetchLogout]);
  return (
    
        {/* 包裹全部组件 */}
           
    
  );
  );  
};

然后在Home组件可以通过store.getState()获取登录的一些数据

import React, { useCallback, useEffect, useState } from "react";
import store from '@src/store';
const Home= () => {
  console.log(store.getState())
  return (
    <>
    
  );
};

export default Home;

用redux 和 localStorage都可以全局存储数据

你可能感兴趣的:(react-redux 和 redux)