【Redux–RTK】React中Redux之RTK的基本使用
1、下载依赖
npm i react-redux @reduxjs/toolkit
2、src/store/index.js中
//使用RTK来构造store import {configureStore} from "@reduxjs/toolkit"; import {stuReducer} from "./stuSlice.js"; import {schoolReducer} from "./schoolSlice.js"; //创建store 用来创建store对象,需要传入一个配置对象作为参数 const store = configureStore({ reducer:{ student:stuReducer, school:schoolReducer } }); export default store;
3、store/stuSlice.js中
import {createSlice} from "@reduxjs/toolkit"; //createSlice 创建reducer的切片 //它需要一个配置对象作为参数,通过对象的不同属性来指定它的配置 const stuSlice = createSlice({ name:'stu', //用来自动生成action中的type initialState:{ //state的初始值 name:'孙悟空', age:18, gender:'男', address:'花果山' }, reducers:{ //指定state的各种操作,直接在对象中添加方法 //修改姓名的方法 setName(state,action){ /** * 可以通过不同的方法来指定对state的不同操作 * 两个参数:state这个state是一个代理对象,可以直接修改 * action.payload是传递过来的参数 * */ state.name = action.payload; }, //修改年龄的方法 setAge(state,action){ state.age = action.payload; } } }) /** * 切片对象会自动的帮助我们生成action * action中存储的是slice自动生成action创建器(函数),调用函数后会自动创建action对象 * action对象的结构{type:name/函数名,payload:函数的参数} * */ export const {setName,setAge} = stuSlice.actions; export const {reducer:stuReducer} = stuSlice;
4、store/schoolSlice.js中
//创建学校的slice import {createSlice} from "@reduxjs/toolkit"; const schoolSlice = createSlice({ name:'school', initialState:{ name:'花果山一校', address:'花果山大街22号' }, reducers:{ //修改name的方法 setName(state,action){ state.name = action.payload; }, //修改地址的方法 setAddress(state, action) { state.address = action.payload; } } }) export const {setName,setAddress} = schoolSlice.actions; export const {reducer:schoolReducer} = schoolSlice;
5、main.jsx中
import React from 'react' import ReactDOM from 'react-dom/client' import App from './App' import {Provider} from "react-redux"; import store from "./store/index.js"; ReactDOM.createRoot(document.getElementById('root')).render( <Provider store={store}> <App /> </Provider> )
6、App.jsx中基本使用
import {useDispatch, useSelector} from "react-redux"; import {setName,setAge} from "./store/stuSlice"; import {setName as setSchoolName, setAddress as setSchoolAddress} from "./store/schoolSlice"; function App() { //useSelector()用来加载state中的数据 const {student, school} = useSelector(state => state); //通过useDispatch()来获取派发器对象 const dispatch = useDispatch(); //修改学生的姓名 const setNameHandler = () =>{ dispatch(setName('东小川')); } //修改学生的年龄 const setAgeHandler = () =>{ dispatch(setAge(21)); } return ( <div className="App"> <p> {student.name}------ {student.age}------ {student.gender}------ {student.address}------ </p> <button onClick={setNameHandler}>修改name</button> <button onClick={setAgeHandler}>修改age</button> <hr/> <p> {school.name}------- {school.address}------- </p> <button onClick={()=>dispatch(setSchoolName('高老庄中小学'))}>修改学校名称</button> <button onClick={()=>dispatch(setSchoolAddress('高老庄府前街19号'))}>修改学校地址</button> </div> ) } export default App