自学内容网 自学内容网

React中redux、react-redux、@reduxjs/toolkit状态管理库的使用方式

效果

在这里插入图片描述

下载依赖

npm install redux react-redux @reduxjs/toolkit --save

在src目录下创建文件

在这里插入图片描述

  1. 创建index.ts文件
import { configureStore } from '@reduxjs/toolkit'
import userSlice from './userReducer'

const store = configureStore({
    reducer: {
        user: userSlice.reducer
    }
})
// 订阅 store
// store.subscribe(() => console.log('subscribe: ', store.getState()))

export default store
  1. 创建userReducer.ts文件
import { createSlice } from '@reduxjs/toolkit'

const userSlice = createSlice({
    name: 'user',
    initialState: {
        str: '我是redux未修改前的文字'
    },
    reducers: {
        editStr(state, action) {
            // Redux Toolkit 允许在 reducers 中编写 "mutating" 逻辑。
            // 它实际上并没有改变 state,因为使用的是 Immer 库,检测到“草稿 state”的变化并产生一个全新的,
            // 基于这些更改的不可变的 state
            state.str = action.payload
        }
    }
})
export default userSlice

在入口文件中引用

import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import { Provider } from 'react-redux';
import store from './store/index'

const root = ReactDOM.createRoot(
  document.getElementById('root') as HTMLElement
);

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

在函数式组件中使用

import { useSelector, useDispatch } from 'react-redux'
import { useNavigate } from 'react-router-dom';
import React, { useState } from 'react';
import { Button } from 'antd';

const Home: React.FC = () => {
    const navigate = useNavigate();
    const { str } = useSelector((state:StoreType.State) => state.user)
    let dispatch = useDispatch()

    const [msg] = useState<string>('点击改变redux');

    const handleChange = () => {
        dispatch({
            type: 'user/editStr',
            payload: '我是工作台修改redux后的值'
        })
    }
    return (
        <>
            <h1>工作台</h1>
            <Button type="primary" onClick={handleChange}>{msg}</Button>
            <Button type="primary" onClick={() => navigate('/authMag/userMag')}>跳转到用户页面</Button>
            <h1>{str}</h1>
        </>
    ) 
}

export default Home

在类组件中使用

import React from "react"
import { Button } from 'antd';
import { connect } from "react-redux";
import { Link } from 'react-router-dom'

type PropType = {
    user: {
        str: string
    },
    dispatch: Function
}

type StateType = {
    msg: string
}

class User extends React.Component<PropType, StateType> {
    constructor(props: PropType | Readonly<PropType>) {
        super(props)
        this.state = {
            msg: '点击改变redux'
        }
    }
    componentDidMount() {
        console.log('User-componentDidMount')
    }
    handleChange = () => {
        this.props.dispatch({
            type: 'user/editStr',
            payload: '我是User页修改redux后的值'
        })
    }
    render() {
        const { msg } = this.state
        const { str } = this.props.user
        return (
            <>
                <h1>用户管理</h1>
                <Button type="primary" onClick={this.handleChange}>{msg}</Button>
                <Button type="primary">
                    <Link to="/home">跳转到工作台页面</Link>        
                </Button>
                <h1>{str}</h1>
            </>
        )
    }
}
const mapStateToProps = (state:PropType) => ({
    user: state.user
});

const mapDispatchToProps = (dispatch: Function) => ({
    dispatch
});
export default connect(mapStateToProps, mapDispatchToProps)(User);

原文地址:https://blog.csdn.net/fu983531588/article/details/137889541

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