React 18

React + Redux + Router路由 + TS

安装插件 React Developer、Redux DevTools、极简插件;
babel
classnames库
dayjs

1 React

组件化开发方式、性能优秀(vnode、fiber)、丰富生态、跨平台支持(React native支持ios、安卓)

1.1 下载React项目

利用npx create-react-app react-basic下载项目,下载好项目之后启动项目

package.json中react、react-dom是最核心的包;

index.js:项目入口文件,引入根组件

App.js:项目根组件

index.js文件

index.html文件

1.2 JSX

JSX需要通过解析工具babel,做解析之后才能在浏览器中运行;
https://babeljs.io/

1.3 Hooks

Hooks文章

const [count, setCount] = useState(0);
count 为 状态变量 ,与普通js变量不同的是,状态变量值发生变化 会驱动 视图发生变化 ;

count++ 会改变count 值,但不引发视图更新;想要触发视图更新,必须使用setCount;

javascript 复制代码
let [count, setCount] = useState(0);
const handleClick = () => {
  count++;
  console.log(count); // count变为 1
  setCount(count + 1); // 视图更新后,count展示的结果是2
}

这里的重点是使用新值替换老值,不可以直接修改老值;对象也同理:setForm({...form, name: 'john'});

1.4 classnames库

classnames库

javascript 复制代码
import classNames from 'classnames';
className={classNames('nav-item', { active: type === 'hot' })}

2 Redux

Redux DevTools 扩展程序

Redux:React最常用的集中状态管理工具,可以独立于框架运行;

核心:state、action、reducer
Redux原理

  • Redux Toolkit:工具包;
  • react-redux:链接redux和react组件的中间件;
javascript 复制代码
npx create-react-app react-redux // 使用CRA快速创建React项目
npm i @reduxjs/toolkit react-redux // 安装配套工具
npm run start // 启动项目

在src目录下新建store目录

Redux store配置

React组件: 使用 react-redux注入store;使用/修改store中的数据

index.js文件

javascript 复制代码
import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './modules/counterStore';

// 创建根store组合子模块
const store = configureStore({
  reducer: {
    counter: counterReducer
  }
});

export default store;

React组件index.js文件

javascript 复制代码
import store from './store';
import { Provider } from 'react-redux';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <Provider store={store}>
    <App />
  </Provider>
)
javascript 复制代码
import { useSelector, useDispatch } from 'react-redux';
import { decrement, increment } from '.store//modules/counterStore';

function App() {
  const { count } = useSelector(state => state.counter);
  // 选择counter对应的模块
  const dispatch = useDispatch();
  return (
  	<button onCLick={() => dispatch(decrement(10))}>-10</button>
    <div>{count}</div>
    <button onCLick={() => dispatch(increment(20))}>+20</button>
  )
}

export default App;
相关推荐
guslegend1 小时前
脚手架原理与本地调试:从 bin 软链接到 npm link
前端·npm·node.js·脚手架·前端工程化
海码事务所1 小时前
Google Play 新个人开发者账号上架指南:12 人连续 14 天封闭测试怎么做?
前端
田威AI2 小时前
图片内文字翻译的规格:输入输出、保真、自动化、时间与费用
前端·计算机视觉
不可能片场2 小时前
命令行中文变问号 我用环境变量救了场
前端·electron
lerhxx2 小时前
AI 应用中的上下文管理 —— 从"上下文窗口"到"分层压缩"的工程实践
前端·javascript
骑着蜗牛撵大象3272 小时前
多 Agent 分治协作:MapReduce 模式下的并行扇出与结果归并
前端
用户55318297322 小时前
Flutter iOS 热更新深入 Dart VM:读懂函数入口、解释执行与调用桥接
前端
前端snow2 小时前
为什么大厂要用Postgres + mogodb的框架?
前端
运维有小邓12 小时前
2026年主流AD域管理软件有哪些?
前端
Mickey同学2 小时前
提示词注入:AI 时代的「SQL 注入」
前端