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中reactreact-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最常用的集中状态管理工具,可以独立于框架运行;

核心:stateactionreducer
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;
相关推荐
一 乐6 小时前
婚纱摄影网站|基于ssm + vue婚纱摄影网站系统(源码+数据库+文档)
前端·javascript·数据库·vue.js·spring boot·后端
C_心欲无痕6 小时前
ts - tsconfig.json配置讲解
linux·前端·ubuntu·typescript·json
清沫6 小时前
Claude Skills:Agent 能力扩展的新范式
前端·ai编程
yinuo7 小时前
前端跨页面通信终极指南:方案拆解、对比分析
前端
yinuo7 小时前
前端跨页面通讯终极指南⑨:IndexedDB 用法全解析
前端
xkxnq8 小时前
第二阶段:Vue 组件化开发(第 16天)
前端·javascript·vue.js
烛阴8 小时前
拒绝配置地狱!5 分钟搭建 Three.js + Parcel 完美开发环境
前端·webgl·three.js
xkxnq8 小时前
第一阶段:Vue 基础入门(第 15天)
前端·javascript·vue.js
anyup9 小时前
2026第一站:分享我在高德大赛现场学到的技术、产品与心得
前端·架构·harmonyos
BBBBBAAAAAi10 小时前
Claude Code安装记录
开发语言·前端·javascript