React_Redux
redux
Redux 是一个独立的 JavaScript 状态管理库
npm i redux
redux 三大原则
- 单一数据源: 整个应用的 state只存在于唯一一个 store 中
- state 是只读的: 唯一改变 state 的方法就是触发 action,action 是一个用于描述已发生事件的普通对象
- 使用纯函数来执行修改
核心概念
- state 状态 - state 是只读的, 不推荐直接修改 state 中的原数据, 通过纯函数修改 state
- store 容器 - 管理状态
import {createStore} from "redux"
const store = createstore(reducer)
- getState()获取状态
- dispatch(action)同步发起修改
- action:是一个对象, 对state 的修改动作,{type:"修改描述"}
- subscribe(listener)监听及取消监听状态的变化
- replaceReducer(nextReducer) - reducer 纯函数 - 修改状态的场所
- const reducer = (state,action)=>{
switch(action.type){
case "value" : return newState;
}
}
- 纯函数(用于计算数据)
1. 相同的输入永远返回相同的输出, 无任何副作用
2. 不修改函数的原有输入值,生成新值
3. 不依赖外部环境状态
- 好处
1. 便于测试
2. 有利重构
react-redux
react项目中的 redux 绑定库
npm i react-redux
-
- connect( state => return {count: state.count})(Count)高阶函数 -从全部state中得到想要的state对象,返回一个函数
-
- useStore 获取 store
-
- useDispatch 获取 dispatch
-
- useSelector 获取 state
中间件
更新的过程中,去做一些其他的事情,
dispatch ---> reducer 更新state
dispatch --> 中间件 --> reducer
异步操作中间件redux-thunk
dispatch接受参数类型:
- 参数action是对象,dispatch-->直接调用 reducer -(同步)
- ⭐参数action是函数,dispatch--> 调用该函数fn(dispatch,getState)->dispatch-->reducer -(异步)
杂七杂八
严格模式(Strict Mode)
<React.StrictMode> </React.StrictMode>
识别具有不安全生命周期的组件
有关旧式字符串ref用法的警告
检测意外的副作用
检测遗留 context API
CSS Modules
- CSS Modules 使用
import style from “[name].module.css”- 局部(默认) 使用- .className = style.className
- 全局 :global(.className){
} - composes: 样式中引入其他样式
Ant Design
- 使用
- 安装 npm install antd
- 引入
import 'antd/dist/antd.css';
import { 组件 } from 'antd';
- 自定义主题
- npm i @craco/craco
craco (一个对 create-react-app 进行自定义配置的社区解决方案) - 修改 package.json
"scripts": {- "start": "react-scripts start",
- "build": "react-scripts build",
- "test": "react-scripts test",
- "start": "craco start",
- "build": "craco build",
- "test": "craco test",
}
- 创建一个 craco.config.js 用于修改默认配置
/* craco.config.js */ module.exports = { // ... }; - 安装 $ yarn add craco-less
- 修改 craco.config.js 配置
const CracoLessPlugin = require('craco-less'); module.exports = { plugins: [ { plugin: CracoLessPlugin, options: { lessLoaderOptions: { lessOptions: { modifyVars: { '@primary-color': '#1DA57A' }, javascriptEnabled: true, }, }, }, }, ], }; - npm i @craco/craco
浙公网安备 33010602011771号