$ npm install @reduxjs/toolkit react-redux
用于存储数据和方法
// src/store/index.ts
import {configureStore, createSlice} from '@reduxjs/toolkit';
// 登录模块
export const loginSlice = createSlice({
name: 'login',
initialState: {
userInfo: null,
},
reducers: {
// 获取用户信息
getUserInfo: (state: any, action) => {
state.userInfo = action.payload;
},
// 清除用户信息
cleanUserInfo: (state) => {
state.userInfo = null;
}
},
})
export const {getUserInfo, cleanUserInfo} = loginSlice.actions;
export default configureStore({
reducer: loginSlice.reducer,
})
添加全局组件为要监听的组件
// src/main.tsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import {HashRouter} from "react-router-dom";
import {Provider} from 'react-redux'
import store from './store'
import App from './App';
import './index.css';
ReactDOM.createRoot(document.getElementById('root') as HTMLElement)
.render(
<HashRouter>
<Provider store={store}>
<App/>
</Provider>
</HashRouter>
)
使用store中存储的方法和属性
// src/views/Login/Login.tsx
import {Button, Card, Checkbox, Col, Form, Input, message, Row} from 'antd';
import React from 'react';
import {useDispatch, useSelector} from 'react-redux';
import {getUserInfo, cleanUserInfo} from '../../store';
import {useNavigate} from "react-router-dom";
const Login: React.FC = () => {
const userInfo = useSelector((state: any) => state.userInfo);
const dispatch = useDispatch();
const navigate = useNavigate();
// 成功调用
const onFinish = (values: any) => {
message.success('登录成功!');
console.log('Success:', values);
dispatch(getUserInfo(values));
navigate('/', {replace: true});
};
// 失败调用
const onFinishFailed = (errorInfo: any) => {
message.error('请检查账号密码是否正确!');
console.log('Failed:', errorInfo);
dispatch(cleanUserInfo());
};
return (
<Row style={{padding: '10px'}}>
<Col span={16} offset={4}>
<Card title={'登录 ---> ' + JSON.stringify(userInfo)}>
<Form name="basic" labelCol={{span: 2}} wrapperCol={{span: 22}} initialValues={{remember: true}}
onFinish={onFinish} onFinishFailed={onFinishFailed} autoComplete="off">
<Form.Item label="账号" name="username" rules={[{required: true, message: '请输入账号!'}]}>
<Input/>
</Form.Item>
<Form.Item label="密码" name="password" rules={[{required: true, message: '请输入密码!'}]}>
<Input.Password/>
</Form.Item>
<Form.Item name="remember" valuePropName="checked" wrapperCol={{offset: 2, span: 22}}>
<Checkbox>记住密码</Checkbox>
</Form.Item>
<Form.Item wrapperCol={{offset: 2, span: 22}}>
<Button type="primary" htmlType="submit">登 录</Button>
</Form.Item>
</Form>
</Card>
</Col>
</Row>
);
};
export default Login;