store下的index.js
import {configureStore} from "@reduxjs/toolkit"
import counterreducer from "./feature/featur"
export default configureStore({
reducer:{
counter:counterreducer
},
middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(logger)
})
子仓库
import {createSlice} from "@reduxjs/toolkit"
import axios from "axios";
export const conterSlice = createSlice({
name:"counter",
initialState : {
count :1,
title:"redux tookit",
arr:[]
},
reducers:{ // 创建完reducers回自动生成action
fn (state,{payload}) {
console.log(payload);
state.count = state.count + payload.step
},
del (state,action) {
state.count = state.count - 1
},
setArr (state,{payload}) {
console.log(payload);
state.arr = payload
}
}
})
export const {fn,del,setArr} = conterSlice.actions // 抛出这些action
// tookit 内置了thunk
export const getlist = (data)=>{ return (dispatch)=>{
axios.get("/api/list").then(res=>{
console.log(res.data);
dispatch(setArr(data))
})
}
}
export default conterSlice.reducer
组件
import React , {useEffect} from 'react'
import {useSelector,useDispatch} from "react-redux"
import {fn,del,getlist} from "../../store/feature/featur"
function Exam() {
const store = useSelector(state=>state.counter)
const dispatch = useDispatch()
console.log(store);
useEffect(()=>{
dispatch(getlist([1,2,13,4,5]))
},[])
let fn1 = ()=>{
dispatch(fn({step:1}))
}
return (
<div>
<h4>{store.count}</h4>
<button onClick={fn1}>点击</button>
</div>
)
}
export default Exam