1.安装redux
npm install @reduxjs/toolkit react-redux
2.创建切片模块化数据
在Src目录下创建store目录,创建moude目录 创建tab.js
javascript
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
javascript
import { configureStore } from '@reduxjs/toolkit';
import TabData from './modules/tab.js'
export default configureStore({
reducer: {
Tab:TabData
}
})
4.全局注册redux
src/inedx.js
javascript
import {Provider} from 'react-redux'
import store from './store'
root.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>
);
5.在页面获取展示数据
javascript
import { useSelector } from 'react-redux';
const showMenu = useSelector((state) => state.Tab.Collapse);
// state.Tab.Collapse
// Tab是reducer里定义的 Collapse 是initialState 里定义的
6.修改数据
javascript
import {useDispatch} from 'react-redux'
//实例化useDispatch
const dispatch = useDispatch()
dispatch(setCollapse())
//setCollapse 是之前定义修改数据的方法
完整代码
javascript
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