# React-0907 **Repository Path**: kingupdow/react-0907 ## Basic Information - **Project Name**: React-0907 - **Description**: React-router&redux学习 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2023-04-28 - **Last Updated**: 2023-04-28 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README ##### Redux 1.什么是 Redux ``` redux是一个专门做状态管理的js库(不是react插件库) 它可以用在react,angular,vue等项目中,但基本与react配合使用 作用:集中式管理react应用中多个组件共享状态 ``` 2.什么时候需要使用 Redux ``` 你在应用程序的许多地方都需要大量的应用程序状态 应用状态更新频繁 更新该状态的逻辑可能很复杂 该应用程序有一个中型或大型的代码库,并且可能由许多人开发 你需要查看该状态如何随着时间的推移而更新 ``` 3.怎么使用 Redux ```javascript 1、安装react-redux && redux-toolkit yarn add react-redux redux-toolkit 2.创建store仓库 // src/store/index.ts 使用configureStore函数 import { configureStore } from "@reduxjs/toolkit"; import countSlice from './count/countSlice' export default configureStore({ reducer: { countSlice } }) 3.使用redux // src/index.ts import React from "react"; import ReactDOM from "react-dom/client"; import "./index.css"; import App from "./App"; import reportWebVitals from "./reportWebVitals"; import { Provider } from "react-redux"; // 引入react-redux的Provider跟组件 import store from "./store/index" // 引入store仓库 const root = ReactDOM.createRoot( document.getElementById("root") as HTMLElement ); root.render( // 在根组件中传入store对象作为参数 ); reportWebVitals(); 4. 创建切片对象 // src/store/count/countSlice.ts 使用createSlice函数 name值必须配置 import { createSlice } from '@reduxjs/toolkit' export const countSlice = createSlice({ name: 'count', initialState: { countValue: 1, }, reducers: { increment: (state, action) => { state.countValue += action.payload }, decrement: (state, action) => { state.countValue -= action.payload }, } }) export const { increment, decrement } = countSlice.actions export default countSlice.reducer 5.在组件中使用 import { increment, decrement } from "../store/count/countSlice"; import { useDispatch, useSelector } from 'react-redux' export default function Index() { const count = useSelector((state) => state.countSlice.countValue) const dispatch = useDispatch() return (

Redux的学习

计算之后的值 {count}

); } ``` 4.异步 actions redux 的 reducers 无法实现异步函数,我们借助 reactjs-toolkit 的 createAsyncThunk 函数实现异步