美文网首页
react学习(12)

react学习(12)

作者: 哆啦C梦的百宝箱 | 来源:发表于2023-12-27 15:05 被阅读0次
  1. 提交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>

相关文章

网友评论

      本文标题:react学习(12)

      本文链接:https://www.haomeiwen.com/subject/onbrndtx.html