一、react-ToolKit是什么?
Redux工具包,简称RTK。RTK可以帮助我们处理使用Redux过程中的重复性工作,简化Redux中的各种操作。
二、使用步骤
安装 react-redux和react-Toolkit
npm install @reduxjs/toolkit react-redux
我们引出我们今天的第一个configureStore 他的作用跟以前的createStore是一样的但是它集成了很多的东西。他有三个参数
import { configureStore } from "@reduxjs/toolkit";
import counterReducer from '../counterSlice/index'
const store = configureStore(
//reducer: 将slice中的reducer可以组成一个对象传入此处;
//middleware:可以使用参数,传入其他的中间件(自行了解); 默认集成了redux-thunk
//devTools:是否配置devTools工具,默认为true;
{
reducer:{
counter:counterReducer
},
}
)
export default store
引出我们的createSlice,他的作用跟以前的reducer差不多 他只能做同步操作 如果需要异步操作
import { createSlice,createAsyncThunk } from "@reduxjs/toolkit";
import { incrementAsync } from "./actionCreator";
import axios from "axios";
const initialState = {
count: 0,
list: [1],
info:'空值'
}
// 当然你也可以跟以前一样在这个里面的异步函数进行dispatch操作
export const getInfo = createAsyncThunk(
'counter/getInfo',
async (extroInfo,store) => {
const res = await axios.get("http://localhost:3001/list")
console.log(extroInfo,store) //这个extroInfo 就是你dispatch带进来的参数 后面那个参数卆store
store.dispatch(changeInfo(res.data[0].name)) // 可以进行dispatch
}
)
export const counterSlice = createSlice({
name: "counter",
initialState,
reducers: {
increment: (state) => {
state.count += 1;
},
decrement: (state) => {
state.count-=1
},
changeInfo: (state,actions) => {
state.info=actions.payload
}
},
extraReducers (builder) { //有三种状态 一种是pending 打开就是刚开始做 //fulfilled 就是成功了 //rejected 就是失败了
builder.addCase(incrementAsync.pending, () => {
console.log('我被发送了')
})
.addCase(incrementAsync.fulfilled, (state,actions) => {
state.list= actions.payload[0].name
})
.addCase(incrementAsync.rejected, () => {
console.log('我失败了')
})
}
})
export const { increment, decrement,changeInfo } =counterSlice.actions //一定一定要导出你的actions
export default counterSlice.reducer
然后就可以在我们的组件中进行 获取 和派发请求
import React, { memo } from 'react'
import { useSelector,useDispatch } from 'react-redux'
import { increment, decrement } from './counterSlice'
import { incrementAsync, } from './counterSlice/actionCreator'
import { getInfo } from './counterSlice'
const Home = memo(() => {
const {count,list,info } = useSelector((state) => {
return {
count: state.counter.count,
list: state.counter.list,
info:state.counter.info
}
})
const dispatch=useDispatch()
const add = () => {
dispatch(increment())
}
const ded = () => {
dispatch(decrement())
}
const async = () => {
dispatch(incrementAsync())
}
return (
<section>
<p>{count}</p>
<button onClick={add}>+1</button>
<button onClick={ded}>-1</button>
<button onClick={async}>异步操作</button>
<p>{list}</p>
<button onClick={() => { dispatch(getInfo(1)) }}>获取info</button>
<p>{ info}</p>
</section>
)
})
export default Home