自学内容网 自学内容网

在react中 使用redux

1.安装redux

 npm install @reduxjs/toolkit react-redux

2.创建切片模块化数据

在Src目录下创建store目录,创建moude目录 创建tab.js

import { createSlice } from '@reduxjs/toolkit';
const tabSlice = createSlice({
  name: 'tab',
  initialState: {
      Collapse: false,
  },
  reducers: {
    setCollapse:(state,action)=>{
      state.Collapse = !state.Collapse
    }
  }
})
export const {setCollapse} = tabSlice.actions
export default tabSlice.reducer

3.创建store

在store目录下创建index.js

import { configureStore } from '@reduxjs/toolkit';
import TabData from './modules/tab.js'
export default configureStore({
    reducer: {
      Tab:TabData
    }
})

4.全局注册redux

src/inedx.js

import {Provider} from 'react-redux'
import store from './store'

root.render(
  <React.StrictMode>
    <Provider store={store}>
      <App />
    </Provider>
  </React.StrictMode>
);

 5.在页面获取展示数据

import { useSelector } from 'react-redux';

 const showMenu = useSelector((state) => state.Tab.Collapse);
//  state.Tab.Collapse
// Tab是reducer里定义的   Collapse 是initialState 里定义的

6.修改数据

import {useDispatch} from 'react-redux'
//实例化useDispatch
const dispatch = useDispatch()


dispatch(setCollapse())
//setCollapse 是之前定义修改数据的方法

完整代码

import React from 'react';
import { Layout,Button,Avatar,Dropdown } from 'antd';
import './index.css';
import { MenuFoldOutlined } from '@ant-design/icons';
import {useDispatch} from 'react-redux'
import {setCollapse} from '../../../../store/modules/tab'
const { Header } = Layout;
const url = 'https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg';
const ComHeader = ({showMenu2}) => {
  const dispatch = useDispatch()
  const isShow = () => {
    dispatch(setCollapse())
  }
  const items = [
    {
      key: '1',
      // eslint-disable-next-line jsx-a11y/anchor-is-valid
      label: (<a>个人中心</a>),
    },
    {
      key: '2',
      // eslint-disable-next-line jsx-a11y/anchor-is-valid
      label: (<a onClick={()=>logout}>退出</a>),
    },
  ];
  return (
    <Header className='header-container'>
      <Button type="text" icon={<MenuFoldOutlined></MenuFoldOutlined>} style={{color: 'white',fontSize:'18px'}} onClick={()=>{isShow()}}>
      </Button>
      <Dropdown menu={{ items }}>
        <Avatar src={<img src={url} alt="avatar" />} />
      </Dropdown>
      
    </Header>
  )
}
export default ComHeader


原文地址:https://blog.csdn.net/big_borther6/article/details/142303663

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!