关于@reduxjs/toolkit和react-redux的使用

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值