1.npm
i react-redux @reduxjs/toolkit
2.
// store/index.js
import
{
configureStore
}
from
'@reduxjs/toolkit'
;
import
counter
from
'./modules/Counter'
// 1.
创建
store
const
store
=
configureStore
({
reducer
: {
counter
}
})
export default
store
3.
// store/modules/Counter.js
import
{
createSlice
}
from
'@reduxjs/toolkit'
;
const
counterSlice
=
createSlice
({
name
:
'counter'
,
//
命名空间
initialState
: {
//
初始化数据的
num
:
0
},
reducers
: {
//
改变数量的
reducer
changeNum
: (
state
,
actions
)
=>
{
state
.
num
+=
actions
.
payload
;
}
}
})
// reduxjs toolkit
把
reducer
和
actions
合并在一起了
export const
{
changeNum
}
=
counterSlice
.
actions
;
//
到处
reducer
export default
counterSlice
.
reducer
;
4.
import
React
from
'react'
;
import
ReactDOM
from
'react-dom/client'
;
import
App
from
'./App'
;
import
{
Provider
}
from
'react-redux'
import
store
from
'./store'
const
root
=
ReactDOM
.
createRoot
(
document
.
getElementById
(
'root'
));
root
.
render
(
<React.StrictMode>
<Provider
store
={
store
}
>
<App />
</Provider>
</React.StrictMode>
)
5.
import
{
Component
}
from
'react'
import
{
connect
}
from
'react-redux'
import
{
changeNum
}
from
'../store/modules/Counter'
;
// UI
组件
class
CounterUI
extends
Component
{
render
() {
// console.log(this.props)
return
(
<div>
<button
onClick
={ ()
=>
this
.
props
.
changeNum
(
1
) }
>
+
</button>
<span>
{
this
.
props
.
num
}
</span>
<button
onClick
={ ()
=>
this
.
props
.
changeNum
(
-
1
) }
>
-
</button>
</div>
)
}
}
//
获取
store
中的数据的方法
const
mapstateFromProps
=
state
=>
{
// state: store
仓库中的数据
// console.log(state)
return
{
num
:
state
.
counter
.
num
}
}
//
修改
store
中的数据的方法
const
mapDispatchFromProps
=
dispatch
=>
{
return
{
changeNum
:
num
=>
{
//
调用
dispatch
方法,传递
actions
dispatch
(
changeNum
(
num
))
}
}
}
//
容器组件
const
Counter
=
connect
(
mapstateFromProps
,
mapDispatchFromProps
)(
CounterUI
);
export default
Counter