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