提交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>