当前位置:   article > 正文

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

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

效果

在这里插入图片描述

下载依赖

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

在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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

在入口文件中引用

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>
);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

在函数式组件中使用

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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

在类组件中使用

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);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/465542
推荐阅读
相关标签
  

闽ICP备14008679号