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;
相关推荐
22x艾克斯9 分钟前
JS中的上下文
开发语言·前端·javascript
佩淇呢1 小时前
vue 跳转新窗口的方法
前端·javascript·vue.js
ScriptEcho1 小时前
Rough.js在Vue3中生成随机蒙德里安风格的抽象艺术
前端
经海路大白狗1 小时前
前端小白成长记:适合练手的开源项目推荐
前端·javascript·学习
打酱油的;1 小时前
layui-页面布局
前端·css·html
朱师磊2 小时前
elementUI的搭建使用过程
前端·javascript·elementui
亲亲晴崽2 小时前
elementui 表格前端自主排序,自主分页
前端·javascript·elementui
行走的茶白2 小时前
vue2+TS,el-table表格单选的写法
前端·javascript·vue.js
xiongxianhe2 小时前
【SpringBoot Web框架实战教程(开源)】01 使用 pom 方式创建 SpringBoot 第一个项目
前端·spring boot·开源
diygwcom2 小时前
重磅更新-UniApp自定义字体可视化设计
前端·javascript·uni-app