RTK(react toolkit)

npm install @reduxjs/toolkit react-redux

核心的API

//编写react代码,并且通过react渲染对应的内容
import React from "react"
import ReactDOM from "react-dom/client"
import App from "./App"
import {Provider} from 'react-redux'
import store from './store/index'

const root = ReactDOM.createRoot(document.querySelector("#root"))
root.render(
    <Provider store={store}>
        <App/>
    </Provider>

)
//---------------------App.js-----------
import React, { PureComponent } from 'react'
import Home from './pages/Home'
import Profile from './pages/Profile'
import './style.css'
import {connect} from 'react-redux'

export class App extends PureComponent {
  render() {
    const {counter} = this.props
    return (
      <div>
        <h2>App Counter:{counter}</h2>
        <div className='pages'>
            <Home/>
            <Profile/>
        </div>
      </div>
    )
  }
}
const MapStateTOProps = (state)=>({
    counter:state.counter.counter
})
export default connect(MapStateTOProps)(App)
//----------------home---------------------
import React, { PureComponent } from 'react'
import {connect} from 'react-redux'
import {addNumber} from '../store/features/counter'

export class Home extends PureComponent {
addNum(num){
  this.props.subNumber2(num)
}
  render() {
    const {counter} = this.props
    return (
      <div>
        <h2>Home Counter:{counter}</h2>
        <button onClick={e=>this.addNum(2)}>+2</button>
        <button onClick={e=>this.addNum(10)}>+10</button>
      </div>
    )
  }
}
const mapStateToProps = (state)=>({
    counter:state.counter.counter
    
})
const mapDispatchTpProps = dispatch =>({
  subNumber2(num){
    dispatch(addNumber(num))
  }

})

export default connect(mapStateToProps,mapDispatchTpProps)(Home)

创建Store

import {configureStore} from '@reduxjs/toolkit'
import CounterReducer from './features/counter'

const  store = configureStore({
    reducer:{
        counter: CounterReducer
    }
})
export default store

//--------------reduce-------------


import {createSlice} from '@reduxjs/toolkit'

const counterSlice = createSlice({
    name: "counter",
    initialState: {
        counter: 100
    },
    reducers:{                                  //state=defaultState,action
        addNumber(state,action){   //相当于case1 语句
           const payload = action.payload
           state.counter =state.counter+payload //内部创建新的state

        },
        subNumber(state,{payload}){  //case 2
        //    const payload = action.payload
            state.counter = state.counter-payload
        }
        
    }
    
})

export default counterSlice.reducer  // CounterSlice是个片段 需要拿到里面的reduce

export const {addNumber,subNumber} = counterSlice.actions

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值