效果
下载依赖
npm install redux react- redux @reduxjs/ toolkit -- save
在src目录下创建文件
创建index.ts文件
import { configureStore } from '@reduxjs/toolkit'
import userSlice from './userReducer'
const store = configureStore ( {
reducer: {
user: userSlice. reducer
}
} )
export default store
创建userReducer.ts文件
import { createSlice } from '@reduxjs/toolkit'
const userSlice = createSlice ( {
name : 'user' ,
initialState : {
str : '我是redux未修改前的文字'
} ,
reducers : {
editStr ( state, action ) {
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) ;