react学习(12)

简介: react学习(12)

提交action传参
在reducers的同步修改方法中添加action对象参数,在调用actionCreater的时候传递参数,参数会被传递到action对象payload属性上

import {
   createSlice} from '@reduxjs/toolkit'
const counterStore = createSlice({
   
  name:'counter',
  initialState:{
   count:0},
  //修改状态的方法,同步方法,支持直接修改
  reducers:{
   
    increment(state){
   
      state.count++
    },
    decrement(state){
   
      state.count--
    },
    addToNum(state,action){
   
      state.count = action.payload
    }
  }
})
//解构出来actionCreater函数
const {
   increment,decrement,addToNum} = counterStore.actions
//获取reducer
const reducer = counterStore.reducer
//以按需导出的方式熬出actionCreater
export {
   increment,decrement}
//以默认导出的方式导出reducer
export default reducer

import {
   useSelector,useDispatch} from 'react-redux'
import {
   increment,decrement} from './store/modules/counterStore'
const {
   count} = useSelector(state => state.counter)
const dispatch = useDispatch()
<div>
    <button onClick={
   ()=>dispatch(addToNum(10))}>add to 10</button>
    <button onClick={
   ()=>dispatch(addToNum(20))}>add to 20</button>
    {
   count}
</div>
相关文章
|
7天前
|
JavaScript 前端开发
react学习(3)创建虚拟dom的两种方式
react学习(3)创建虚拟dom的两种方式
146 66
|
7天前
|
前端开发 JavaScript 算法
react学习(1)
react学习(1)
119 66
|
7天前
|
前端开发 JavaScript
react学习(5)
react学习(5)
163 59
|
7天前
|
前端开发
react学习(2)
react学习(2)
124 57
|
6天前
|
前端开发
react学习(7)
react学习(7)
88 45
|
1天前
|
前端开发
react学习(17)回调形式的ref
react学习(17)回调形式的ref
|
2天前
|
前端开发
react学习(15)函数式组件中使用props
react学习(15)函数式组件中使用props
|
2天前
|
前端开发 JavaScript
react学习(13)props
react学习(13)props
|
1天前
|
存储 前端开发 容器
react学习(18)createRef形式的ref
react学习(18)createRef形式的ref
|
2天前
|
前端开发
react学习(14)类式组件的构造器与props
react学习(14)类式组件的构造器与props