当前位置: 首页 > news >正文

网站设计做哪些准备最新公告哈尔滨

网站设计做哪些准备,最新公告哈尔滨,公司邮箱后缀有哪些,深圳开发网站的公司哪家好黑马React: Redux Date: November 19, 2023 Sum: Redux基础、Redux工具、调试、美团案例 Redux介绍 Redux 是React最常用的集中状态管理工具#xff0c;类似于Vue中的Pinia#xff08;Vuex#xff09;#xff0c;可以独立于框架运行 作用#xff1a;通过集中管理的方式管…黑马React: Redux Date: November 19, 2023 Sum: Redux基础、Redux工具、调试、美团案例 Redux介绍 Redux 是React最常用的集中状态管理工具类似于Vue中的PiniaVuex可以独立于框架运行 作用通过集中管理的方式管理应用的状态 为什么要使用Redux 独立于组件无视组件之间的层级关系简化通信问题单项数据流清晰易于定位bug调试工具配套良好方便调试 Redux快速体验 1. 实现计数器 需求不和任何框架绑定不使用任何构建工具使用纯Redux实现计数器 使用步骤 定义一个 reducer 函数 根据当前想要做的修改返回一个新的状态使用createStore方法传入 reducer函数 生成一个store实例对象使用store实例的 subscribe方法 订阅数据的变化数据一旦变化可以得到通知使用store实例的 dispatch方法提交action对象 触发数据变化告诉reducer你想怎么改数据使用store实例的 getState方法 获取最新的状态数据更新到视图中 代码实现 button iddecrement-/button span idcount0/span button idincrement/buttonscript srchttps://unpkg.com/reduxlatest/dist/redux.min.js/scriptscript// 定义reducer函数// 内部主要的工作是根据不同的action 返回不同的statefunction counterReducer (state { count: 0 }, action) {switch (action.type) {case INCREMENT:return { count: state.count 1 }case DECREMENT:return { count: state.count - 1 }default:return state}}// 使用reducer函数生成store实例const store Redux.createStore(counterReducer)// 订阅数据变化store.subscribe(() {console.log(store.getState())document.getElementById(count).innerText store.getState().count})// 增const inBtn document.getElementById(increment)inBtn.addEventListener(click, () {store.dispatch({type: INCREMENT})})// 减const dBtn document.getElementById(decrement)dBtn.addEventListener(click, () {store.dispatch({type: DECREMENT})}) /script2. Redux数据流架构 Redux的难点是理解它对于数据修改的规则, 下图动态展示了在整个数据的修改中数据的流向 为了职责清晰Redux代码被分为三个核心的概念我们学redux其实就是学这三个核心概念之间的配合三个概念分别是: state: 一个对象 存放着我们管理的数据action: 一个对象 用来描述你想怎么改数据reducer: 一个函数 根据action的描述更新state Redux与React - 环境准备 Redux虽然是一个框架无关可以独立运行的插件但是社区通常还是把它与React绑定在一起使用以一个计数器案例体验一下Redux React 的基础使用 1. 配套工具 在React中使用redux官方要求安装俩个其他插件 - Redux Toolkit 和 react-redux Redux ToolkitRTK- 官方推荐编写Redux逻辑的方式是一套工具的集合集简化书写方式react-redux - 用来 链接 Redux 和 React组件 的中间件 2. 配置基础环境 使用 CRA 快速创建 React 项目 npx create-react-app react-redux安装配套工具 npm i reduxjs/toolkit react-redux启动项目 npm run start3. store目录结构设计 通常集中状态管理的部分都会单独创建一个单独的 store 目录应用通常会有很多个子store模块所以创建一个 modules 目录在内部编写业务分类的子storestore中的入口文件 index.js 的作用是组合modules中所有的子模块并导出store Redux与React - 实现counter 1. 整体路径熟悉 2. 使用 React Toolkit 创建 counterStore modules/counterStore.js import { createSlice } from reduxjs/toolkitconst counterStore createSlice({// 模块名称独一无二name: counter,// 初始数据initialState: {count: 1},// 修改数据的同步方法 支持直接修改reducers: {increment (state) {state.count},decrement(state){state.count--}} }) // 解构出actionCreater const { increment,decrement } counterStore.actions// 获取reducer函数 const counterReducer counterStore.reducer// 导出 export { increment, decrement } export default counterReducerstore/index.js import { configureStore } from reduxjs/toolkitimport counterReducer from ./modules/counterStoreexport default configureStore({reducer: {// 注册子模块counter: counterReducer} })3. 为React注入store react-redux负责把Redux和React 链接 起来内置 Provider组件 通过 store 参数把创建好的store实例注入到应用中链接正式建立 src/index.js import React from react import ReactDOM from react-dom/client import App from ./App // 导入store import store from ./store // 导入store提供组件Provider import { Provider } from react-reduxReactDOM.createRoot(document.getElementById(root)).render(// 提供store数据Provider store{store}App //Provider )✅4. React组件使用store中的数据 - useSelector 在React组件中使用store中的数据需要用到一个钩子函数 - useSelector它的作用是把store中的数据映射到组件中使用样例如下 useSelector作用把store中的数据映射到组件中 注上面是组件counterStore下面是store/index.js. 即根组件 src/App.js import { useDispatch ,useSelector } from react-redux import { increment, decrement, addToNum } from ./store/modules/counterStore1function App() {const { count } useSelector(state state.counter )const dispatch useDispatch()return (div classNameAppbutton onClick{() dispatch(decrement())}-/button{ count }button onClick{() dispatch(increment())}/buttonbutton onClick{() dispatch(addToNum)}add to 10/buttonbutton onClick{() dispatch(addToNum)}add to 20/button/div) }export default App✅5. React组件修改store中的数据 - dispatch React组件中修改store中的数据需要借助另外一个hook函数 - useDispatch它的作用是生成提交action对象的dispatch函数 dispatch作用在组件中提交action对象从而修改store中数据 使用样例如下 ✅Redux与React - 提交action传参 需求组件中有俩个按钮2 add to 10和 add to 20可以直接把count值修改到对应的数字目标count值是在组件中传递过去的需要在提交action的时候传递参数 实现方式利用action传参实现 1-在reducers的同步修改方法中添加action对象参数 在调用actionCreater的时候传递参数参数会被传递到action对象payload属性上 理解这边直接理解 addToNum 接受的参数会被传递到 action.payload 即可 总结: 组件中使用哪个hook函数获取store中的数据 useSelector组件中使用哪个hook函数获取dispatch方法 useDispatch如何得到要提交action对象 执行store模块中导出的actionCreater方法 Redux与React - 异步action处理 需求理解 实现步骤 创建store的写法保持不变配置好同步修改状态的方法 单独封装一个函数在函数内部return一个新函数在新函数中 2.1 封装异步请求获取数据 2.2 调用同步actionCreater传入异步数据生成一个action对象并使用dispatch提交 组件中dispatch的写法保持不变 代码实现 测试接口地址 http://geek.itheima.net/v1_0/channels modules/channelStore.js import { createSlice } from reduxjs/toolkit import axios from axiosconst channelStore createSlice({name: channel,initialState: {channelList: []},reducers: {setChannelList (state, action) {state.channelList action.payload}} })// 创建异步 const { setChannelList } channelStore.actions const url http://geek.itheima.net/v1_0/channels // 封装一个函数 在函数中return一个新函数 在新函数中封装异步 // 得到数据之后通过dispatch函数 触发修改 const fetchChannelList () {return async (dispatch) {const res await axios.get(url)dispatch(setChannelList(res.data.data.channels))} }export { fetchChannelList }const channelReducer channelStore.reducer export default channelReducersrc/App.js import { useEffect } from react import { useSelector, useDispatch } from react-redux import { fetchChannelList } from ./store/channelStorefunction App () {// 使用数据const { channelList } useSelector(state state.channel)useEffect(() {dispatch(fetchChannelList())}, [dispatch])return (div classNameAppul{channelList.map(task li key{task.id}{task.name}/li)}/ul/div) }export default AppRedux-React链路过程 Redux调试 - devtools Redux官方提供了针对于Redux的调试工具支持实时state信息展示action提交信息查看等 工具处理: 美团小案例 1. 案例演示 基本开发思路 使用 RTKRedux Toolkit来管理应用状态, 组件负责 数据渲染 和 dispatch action 2. 准备并熟悉环境 克隆项目到本地内置了基础静态组件和模版 git clone http://git.itcast.cn/heimaqianduan/redux-meituan.git安装所有依赖 npm i启动mock服务内置了json-server npm run serve启动前端服务 npm run start3. 分类和商品列表渲染 1- 编写store逻辑 // 编写store import { createSlice } from reduxjs/toolkit import axios from axiosconst foodsStore createSlice({name: foods,initialState: {// 商品列表foodsList: []},reducers: {// 更改商品列表setFoodsList (state, action) {state.foodsList action.payload}} })// 异步获取部分 const { setFoodsList } foodsStore.actions const fetchFoodsList () {return async (dispatch) {// 编写异步逻辑const res await axios.get(http://localhost:3004/takeaway)// 调用dispatch函数提交actiondispatch(setFoodsList(res.data))} }export { fetchFoodsList }const reducer foodsStore.reducerexport default reducer2- 组件使用store数据 // 省略部分代码 import { useDispatch, useSelector } from react-redux import { fetchFoodsList } from ./store/modules/takeaway import { useEffect } from reactconst App () {// 触发action执行// 1. useDispatch - dispatch 2. actionCreater导入进来 3.useEffectconst dispatch useDispatch()useEffect(() {dispatch(fetchFoodsList())}, [dispatch])return (div classNamehome{/* 导航 */}NavBar /{/* 内容 */}div classNamecontent-wrapdiv classNamecontentMenu /div classNamelist-contentdiv classNamegoods-list{/* 外卖商品列表 */}{foodsList.map(item {return (FoodsCategorykey{item.tag}// 列表标题name{item.name}// 列表商品foods{item.foods}/)})}/div/div/div/div{/* 购物车 */}Cart //div) }export default App4. 点击分类激活交互实现 1- 编写store逻辑 // 编写storeimport { createSlice } from reduxjs/toolkit import axios from axiosconst foodsStore createSlice({name: foods,initialState: {// 菜单激活下标值activeIndex: 0},reducers: {// 更改activeIndexchangeActiveIndex (state, action) {state.activeIndex action.payload}} })// 导出 const { changeActiveIndex } foodsStore.actionsexport { changeActiveIndex }const reducer foodsStore.reducerexport default reducer2- 编写组件逻辑 const Menu () {const { foodsList, activeIndex } useSelector(state state.foods)const dispatch useDispatch()const menus foodsList.map(item ({ tag: item.tag, name: item.name }))return (nav classNamelist-menu{/* 添加active类名会变成激活状态 */}{menus.map((item, index) {return (div// 提交action切换激活indexonClick{() dispatch(changeActiveIndex(index))}key{item.tag}// 动态控制active显示className{classNames(list-menu-item,activeIndex index active)}{item.name}/div)})}/nav) }5. 商品列表切换显示 image.png div classNamelist-contentdiv classNamegoods-list{/* 外卖商品列表 */}{foodsList.map((item, index) {return (activeIndex index FoodsCategorykey{item.tag}// 列表标题name{item.name}// 列表商品foods{item.foods}/)})}/div /div6. 添加购物车实现 1- 编写store逻辑 // 编写storeimport { createSlice } from reduxjs/toolkit import axios from axiosconst foodsStore createSlice({name: foods,reducers: {// 添加购物车addCart (state, action) {// 是否添加过以action.payload.id去cartList中匹配 匹配到了 添加过const item state.cartList.find(item item.id action.payload.id)if (item) {item.count} else {state.cartList.push(action.payload)}}} })// 导出actionCreater const { addCart } foodsStore.actionsexport { addCart }const reducer foodsStore.reducerexport default reducer关键 a.判断商品是否添加过 // 是否添加过以action.payload.id去cartList中匹配 匹配到了 添加过 const item state.cartList.find(item item.id action.payload.id)2- 编写组件逻辑 div classNamegoods-count{/* 添加商品 */}spanclassNameplusonClick{() dispatch(addCart({id,picture,name,unit,description,food_tag_list,month_saled,like_ratio_desc,price,tag,count}))}/span /divBug修复 修复count增加问题 7. 统计区域实现 image.png 实现思路 基于store中的cartList的length渲染数量基于store中的cartList累加price * count购物车cartList的length不为零则高亮 // 计算总价 const totalPrice cartList.reduce((a, c) a c.price * c.count, 0){/* fill 添加fill类名购物车高亮*/} {/* 购物车数量 */} div onClick{onShow} className{classNames(icon, cartList.length 0 fill)}{cartList.length 0 div classNamecartCornerMark{cartList.length}/div} /div拓展 react中不存在computed计算属性因为每次数值的变化都会引起组件的重新渲染 8. 购物车列表功能实现 image.png 1-控制列表渲染 const Cart () {return (div classNamecartContainer{/* 添加visible类名 div会显示出来 */}div className{classNames(cartPanel, visible)}{/* 购物车列表 */}div classNamescrollArea{cartList.map(item {return (div classNamecartItem key{item.id}img classNameshopPic src{item.picture} alt /div classNamemaindiv classNameskuInfodiv classNamename{item.name}/div/divdiv classNamepayableAmountspan classNameyuan¥/spanspan classNameprice{item.price}/span/div/divdiv classNameskuBtnWrapper btnGroup{/* 数量组件 */}Countcount{item.count}//div/div)})}/div/div/div) }export default Cart2- 购物车增减逻辑实现 // count增 increCount (state, action) {// 关键点找到当前要修改谁的count idconst item state.cartList.find(item item.id action.payload.id)item.count }, // count减 decreCount (state, action) {// 关键点找到当前要修改谁的count idconst item state.cartList.find(item item.id action.payload.id)if (item.count 0) {return}item.count-- }div classNameskuBtnWrapper btnGroup{/* 数量组件 */}Countcount{item.count}onPlus{() dispatch(increCount({ id: item.id }))}onMinus{() dispatch(decreCount({ id: item.id }))}/ /div3-清空购物车实现 // 清除购物车clearCart (state) { state.cartList []}div classNameheaderspan classNametext购物车/spanspanclassNameclearCartonClick{() dispatch(clearCart())}清空购物车/span /div9. 控制购物车显示和隐藏 image.png // 控制购物车打开关闭的状态 const [visible, setVisible] useState(false)const onShow () {if (cartList.length 0) {setVisible(true)} }{/* 遮罩层 添加visible类名可以显示出来 */} divclassName{classNames(cartOverlay, visible visible)}onClick{() setVisible(false)} /
http://www.zqtcl.cn/news/903609/

相关文章:

  • 国外mod大型网站财税公司
  • 一个很好的个人网站开发做一个简单网页多少钱
  • 东莞在哪里学网站建设网站建设团队与分工
  • 网站功能插件昆明网站建设技术研发中心
  • 网站开发培训中心 市桥移动端ui
  • 高碑店地区网站建设上海排名十大装潢公司
  • 无锡自助建站网站还是新能源专业好
  • pc 手机网站 微站如何建设与维护网站
  • 大学生兼职网站开发毕设论文杭州网络排名优化
  • 做教育机器网站网站建设的步骤图
  • 桔子建站是什么平台郑州公司注册网上核名
  • 网站开发技能有哪些网站建设艾金手指科杰
  • 网站建设挂什么费用网站建设学那些课
  • 网站定位与功能分析在互联网公司做网站
  • 安阳网站建设兼职做网站推广有哪些公司
  • 网站制作的一般过程怎么用手机搭建网站
  • 备案 网站名称 怎么改深圳建网站公司
  • html 企业网站模板网站策划书免费
  • 网站建设销售ppt拖拽建站系统源码
  • 网站托管费用多少网站的开发流程
  • 周到的商城网站建设北京品牌网站
  • 网站开发费用属于什么科目网站建设考试多选题
  • c asp做网站wordpress4.5.2文章采集
  • 百度网站建设电话建立网站站建设可以吗
  • 网站后台代码在哪修改网站如何做下一页
  • 网站开发职业要求百度推广代理商与总公司的区别
  • 西安网站建设中心网页 网 址网站区别
  • 技术支持东莞网站建设机械seo岗位是什么意思
  • 做商城网站需要备案什么域名硬件开发工具有哪些
  • 网络网站制作技巧wordpress全文