2)react-redux抽离redux
为什么用react-redux?
- redux与react组件的代码耦合度太高
- 编码不够简洁
基本概念
React-Redux将所有组件分成两大类
UI组件
a.只负责 UI 的呈现,不带有任何业务逻辑
b.通过props接收数据(一般数据和函数)
c.不使用任何 Redux 的 API
d.一般保存在components文件夹下
容器组件
a.负责管理数据和业务逻辑,不负责UI的呈现
b.使用 Redux 的 API
c.一般保存在containers文件夹下
相关API
1.Provider
让所有组件都可以得到state数据
<Provider store={store}>
<App />
</Provider>2.connect()
用于包装 UI 组件生成容器组件
import { connect } from 'react-redux'
connect(
mapStateToprops,
mapDispatchToProps
)(Counter)3.mapStateToprops()
将外部的数据(即state对象)转换为UI组件的标签属性
const mapStateToprops = function (state) {
return {
value: state
}
}4.mapDispatchToProps()
将分发action的函数转换为UI组件的标签属性
简洁语法可以直接指定为actions对象或包含多个action方法的对象
下载包 npm install --save react-redux
优化redux:根据 React-Redux组件分类思想,将app.jsx从上一篇的redux内抽离出来
// app.jsx import { connect } from "react-redux"; // 引入action内的方法 import { increment, decrement } from "../redux/actions"; // 引入容器组件 import counter from "../components/counter";export default connect((state) => {// state为store内的count值 即0console.log(state, "state");// 将state状态传给counter组件return { count: state };},// 将increment,decrement方法传给counter{ increment, decrement } )(counter);
// counter.js内 // 导入 React 模块 import React, { Component } from "react";import propTypes from "prop-types";// 暴露并创建react类 export default class App extends Component {static propTypes = {count: propTypes.number.isRequired,increment: propTypes.func.isRequired,decrement: propTypes.func.isRequired,};addCountFn = () => {this.props.increment(this.select.value * 1);};delCountFn = () => {this.props.decrement(this.select.value * 1);};incrementOddFn = () => {const { count } = this.props;if (count % 2 === 1) {this.props.increment(this.select.value * 1);}};incrementAsyncFn = () => {setTimeout(() => {this.props.increment(this.select.value * 1);}, 1000);};render() {const { count } = this.props;return (<div><h2>click {count} times</h2><select ref={(select) => (this.select = select)}><option value="1">1</option><option value="2">2</option><option value="3">3</option></select> <button onClick={this.addCountFn}>+</button> <button onClick={this.delCountFn}>-</button> <button onClick={this.incrementOddFn}>increment if odd</button> <button onClick={this.incrementAsyncFn}>increment async</button></div>);} }
// index.js import React from "react"; import { createRoot } from 'react-dom/client'; import { Provider } from "react-redux";import store from './redux/store' import App from "./containers/app";createRoot(document.getElementById('root')).render(<Provider store={store} ><App /></Provider> );;
上一篇问题:reducers.js如何暴露多个模块
// reducers.js import { COMMENT_ADD, COMMENT_DEL, COMMENT_INIT, INCREMENT, DECREMENT } from "./action-types"; import { combineReducers } from 'redux' const initCommentData = []function comments (state = initCommentData, actions) {switch (actions.type) {// 添加方法case COMMENT_ADD:return [actions.data, ...state]// 删除方法case COMMENT_DEL:return state.filter((comment, index) => index !== actions.data)// 初始化评论case COMMENT_INIT:return actions.data// 默认default:return state} }function counter (state = 0, action) {switch (action.type) {case INCREMENT:return state += action.datacase DECREMENT:return state -= action.datadefault:return state} }export default combineReducers({comments,counter} )
暴露多个模块后,相应的组件 也要做修改
// app.jsx import React, { Component } from "react"; import { connect } from "react-redux"; import PropTypes from "prop-types";import Add from "../../components/commentAdd/commentAdd"; import List from "../../components/commentList/commentList"; import { commentAdd, commentDel, commentAsync } from "../../redux/actions"; import "./app.css";class App extends Component {static propTypes = {commentList: PropTypes.array.isRequired,commentAdd: PropTypes.func.isRequired,commentDel: PropTypes.func.isRequired,commentAsync: PropTypes.func.isRequired,};componentDidMount() {const { commentAsync } = this.props;commentAsync();}render() {const { commentList, commentAdd, commentDel } = this.props;return (<div id="app"><div><header className="site-header jumbotron"><div className="container"><div className="row"><div className="col-xs-12"><h1>请发表对React的评论</h1></div></div></div></header><div className="container"><Add commentAdd={commentAdd} /><List commentList={commentList} commentDel={commentDel} /></div></div></div>);} }export default connect((state) => // 此处为reducers修改后调整 ({ commentList: state.comments }), {commentAdd,commentDel,commentAsync } )(App);
// store.js 存储 状态变量import { configureStore } from '@reduxjs/toolkit'import reducers from './reducers'// 根据comments函数创建store对象const store = configureStore({ reducer: reducers }) console.log(store, 'store'); export default store
redux如何处理异步操作???
redux-thunk处理异步操作_FF_XM的博客-CSDN博客
redux基本概念
redux初体验(问题记录)_FF_XM的博客-CSDN博客
2)react-redux抽离redux相关推荐
- react dispatch_梳理下redux、mobx 在react的应用
❝ 本文整理下近期 redux.mobx 在 react 中的使用对比,大家可以根据个人喜好,合理使用 查看完整 demo ❞ redux 状态管理 redux 基本使用流程 ❝ 首先把 redux ...
- React native 项目进阶(redux, redux saga, redux logger)
之前利用知乎日报的api写了react-native的一个入门项目,传送文章地址React Native 项目入门和源码地址RN入门项目源码,目前github上的代码已经在原文的基础上增加了新的功能, ...
- 【React.js 06】Redux基础知识
Redux是一个专注于状态管理的库,和React是解耦的,用Angular和Vue都可以使用Redux.其具有一个单一状态,单向数据流的特性. Redux概念 redux有一个store,记录所有的s ...
- 优雅的在React项目中使用Redux
概念 首先我们会用到哪些框架和工具呢? React UI框架 Redux 状态管理工具,与React没有任何关系,其他UI框架也可以使用Redux react-redux React插件,作用:方便在 ...
- 如何优雅地在React项目中使用Redux
前言 或许你当前的项目还没有到应用Redux的程度,但提前了解一下也没有坏处,本文不会安利大家使用Redux 概念 首先我们会用到哪些框架和工具呢? React UI框架 Redux 状态管理工具,与 ...
- 如何在React Native中使用Redux Saga监视网络更改
by Pritish Vaidya 通过Pritish Vaidya 如何在React Native中使用Redux Saga监视网络更改 (How to monitor network change ...
- 【转】浅谈React、Flux 与 Redux
本文转自<浅谈React.Flux 与 Redux>,转载请注明出处. React React 是一个 View 层的框架,用来渲染视图,它主要做几件事情: 组件化 利用 props 形成 ...
- React技术栈探究-Redux
React技术栈耕耘 -- Redux Redux 是近年来提出的 Flux 思想的一种实践方案,在它之前也有 reflux . fluxxor 等高质量的作品,但短短几个月就在 GitHub 上获近 ...
- 彻底征服 React.js + Flux + Redux【讲师辅导】-曾亮-专题视频课程
彻底征服 React.js + Flux + Redux[讲师辅导]-74574人已学习 课程介绍 [会员免费]链接 http://edu.csdn.net/lecturer/585 ...
最新文章
- webRTC——浏览器里的音视频通话
- Hibernate的出现和Hinbernate的简单模拟实现
- Kubernetes PV/PVC/StroageClass 持久化存储简介
- 关于递归转换成循环的思想
- 服务器运行几年后搬迁,服务器搬迁之后的准备工作和应对
- (一)数字图像处理基础知识点
- Speedtest在线测试html,配置HTML5 Speedtest测试本地与服务器之间的速度
- Java实现图像增强之伽马变换
- 信捷 XDH Ethercat 正负极限的设置
- 2019年英语四级作文
- 高等数学:第八章 多元函数的微分法及其应用(3)全微分
- Packet Tracer - 使用 CLI 配置 IOS 入侵防御系统 (IPS)
- correl函数_教你利用Correl函数返回相关系数并确定属性关系
- 国外LEAD赚钱深入讲解
- C++程序设计(谭浩强)笔记八
- 第13章 多进程编程
- EXCEL时间计划顺延,并跳过周末以及法定节假日
- LWN:在Linux上用Waydroid运行安卓应用!
- 开放系统理论(3)生物的特征——热力学第二定律,和熵(1吐槽)
- Automatic Plugin -WordPress自动采集插件 v3.56.0
热门文章
- 我也和 chatGPT 聊了聊
- LaTex 论文排版(4): 插入图片(Visio图转换成.eps图)
- python pandas快速上手教程,还不赶紧收藏一波
- 医疗无菌加工之冷冻干燥 –冻干机搁板温度分布验证的指南规范与工艺建议
- iphone OS、Android、Blackberry OS与Palm OS的比较
- 【Python】实现给小仙女定时推送消息
- Elasticsearch(二)
- Python 自学笔记(三)
- 2014年如何找到SEO流量的突破口
- STM32使用串口1配合DMA接收不定长数据,大大减轻CPU载荷。