react+redux教程(一)connect、applyMiddleware、thunk、webpackHotMiddleware

本文主要是介绍react+redux教程(一)connect、applyMiddleware、thunk、webpackHotMiddleware,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

今天,我们通过解读官方示例代码(counter)的方式来学习react+redux。

例子

这个例子是官方的例子,计数器程序。前两个按钮是加减,第三个是如果当前数字是奇数则加一,第四个按钮是异步加一(延迟一秒)。

源代码:https://github.com/lewis617/react-redux-tutorial/tree/master/redux-examples/counter

组件
components/Counter.js

import React, { Component, PropTypes } from 'react'class Counter extends Component {render() {//从组件的props属性中导入四个方法和一个变量const { increment, incrementIfOdd, incrementAsync, decrement, counter } = this.props;//渲染组件,包括一个数字,四个按钮return (<p>Clicked: {counter} times{' '}<button onClick={increment}>+</button>{' '}<button onClick={decrement}>-</button>{' '}<button onClick={incrementIfOdd}>Increment if odd</button>{' '}<button onClick={() => incrementAsync()}>Increment async</button></p>)}
}
//限制组件的props安全
Counter.propTypes = {//increment必须为fucntion,且必须存在increment: PropTypes.func.isRequired,incrementIfOdd: PropTypes.func.isRequired,incrementAsync: PropTypes.func.isRequired,decrement: PropTypes.func.isRequired,//counter必须为数字,且必须存在counter: PropTypes.number.isRequired
};export default Counter

上述代码,我们干了几件事:

从props中导入变量和方法
渲染组件
有的同学可能会急于想知道props的方法和变量是怎么来,下面我们继续解读。

容器
containers/App.js

import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import Counter from '../components/Counter'
import * as CounterActions from '../actions/counter'

//将state.counter绑定到props的counter
function mapStateToProps(state) {return {counter: state.counter}
}
//将action的所有方法绑定到props上
function mapDispatchToProps(dispatch) {return bindActionCreators(CounterActions, dispatch)
}

//通过react-redux提供的connect方法将我们需要的state中的数据和actions中的方法绑定到props上
export default connect(mapStateToProps, mapDispatchToProps)(Counter)

看到这里,很多刚接触redux同学可能已经晕了,我来图解下redux的流程。

state就是数据,组件就是数据的呈现形式,action是动作,action是通过reducer来更新state的。

上述代码,我们干了几件事:

把state的counter值绑定到props上
把四个action创建函数绑定到props上
connect
那么为什么就绑定上去了呢?因为有connect这个方法。这个方法是如何实现的,或者我们该怎么用这个方法呢?connect这个方法的用法,可以直接看api文档。我也可以简单描述一下:

第一个参数,必须是function,作用是绑定state的指定值到props上面。这里绑定的是counter
第二个参数,可以是function,也可以是对象,作用是绑定action创建函数到props上。
返回值,是绑定后的组件
这里还有很多种其他写法,我喜欢在第二个参数绑定一个对象,即

import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import Counter from '../components/Counter'
import * as CounterActions from '../actions/counter'//将state.counter绑定到props的counter
function mapStateToProps(state) {return {counter: state.counter}
}//通过react-redux提供的connect方法将我们需要的state中的数据和actions中的方法绑定到props上
export default connect(mapStateToProps, CounterActions)(Counter)

还可以不写第二个参数,后面用dispatch来触发action的方法,即

import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import Counter from '../components/Counter'
import * as CounterActions from '../actions/counter'//将state.counter绑定到props的counter
function mapStateToProps(state) {return {counter: state.counter}
}//通过react-redux提供的connect方法将我们需要的state中的数据绑定到props上
export default connect(mapStateToProps)(Counter)

后面在组件中直接使用dispatch()来触发action创建函数。

action和reducer两个好基友负责更新state
actions/counter.js

export const INCREMENT_COUNTER = 'INCREMENT_COUNTER'
export const DECREMENT_COUNTER = 'DECREMENT_COUNTER'
//导出加一的方法
export function increment() {return {type: INCREMENT_COUNTER}
}
//导出减一的方法
export function decrement() {return {type: DECREMENT_COUNTER}
}
//导出奇数加一的方法,该方法返回一个方法,包含dispatch和getState两个参数,dispatch用于执行action的方法,getState返回state
export function incrementIfOdd() {return (dispatch, getState) => {//获取state对象中的counter属性值const { counter } = getState()//偶数则返回if (counter % 2 === 0) {return}//没有返回就执行加一dispatch(increment())}
}
//导出一个方法,包含一个默认参数delay,返回一个方法,一秒后加一
export function incrementAsync(delay = 1000) {return dispatch => {setTimeout(() => {dispatch(increment())}, delay)}
}//这些方法都导出,在其他文件导入时候,使用import * as actions 就可以生成一个actions对象包含所有的export

reducers/counter.js

import { INCREMENT_COUNTER, DECREMENT_COUNTER } from '../actions/counter'//reducer其实也是个方法而已,参数是state和action,返回值是新的state
export default function counter(state = 0, action) {switch (action.type) {case INCREMENT_COUNTER:return state + 1case DECREMENT_COUNTER:return state - 1default:return state}
}

reducers/index.js

import { combineReducers } from 'redux'
import counter from './counter'//使用redux的combineReducers方法将所有reducer打包起来
const rootReducer = combineReducers({counter
})export default rootReducer

上述代码我们干了几件事:

写了四个action创建函数
写了reducer用于更新state
将所有reducer(这里只有一个)打包成一个reducer
看到这里,有很多初次接触redux的同学可能已经晕了,怎么那么多概念?为了形象直观,我们在开发工具(react dev tools)上看看这些state,props什么的:

action的方法和state的变量是不是都绑定上去了啊。state怎么看呢?这个需要借助redux的开发工具,也可以通过Connect(Counter)组件的State来查看redux那颗全局唯一的状态树:

那个storeState就是全局唯一的状态树。我们可以看到只有一个counter而已。

注册store
store/configureStore.js

import { createStore, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'
import reducer from '../reducers'//applyMiddleware来自redux可以包装 store 的 dispatch
//thunk作用是使action创建函数可以返回一个function代替一个action对象
const createStoreWithMiddleware = applyMiddleware(thunk
)(createStore)export default function configureStore(initialState) {const store = createStoreWithMiddleware(reducer, initialState)//热替换选项if (module.hot) {// Enable Webpack hot module replacement for reducersmodule.hot.accept('../reducers', () => {const nextReducer = require('../reducers')store.replaceReducer(nextReducer)})}return store
}

index.js

import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import App from './containers/App'
import configureStore from './store/configureStore'const store = configureStore()render(<Provider store={store}><App /></Provider>,document.getElementById('root')
)

上述代码,我们干了几件事:

用中间件使action创建函数可以返回一个function代替一个action对象
如果在热替换状态(Webpack hot module replacement)下,允许替换reducer
导出store
将store放进provider
将provider放在组件顶层,并渲染
applyMiddleware、thunk
applyMiddleware来自redux可以包装 store 的 dispatch()

thunk作用使action创建函数可以返回一个function代替一个action对象

服务
server.js

var webpack = require('webpack')
var webpackDevMiddleware = require('webpack-dev-middleware')
var webpackHotMiddleware = require('webpack-hot-middleware')
var config = require('./webpack.config')var app = new (require('express'))()
var port = 3000var compiler = webpack(config)
app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath }))
app.use(webpackHotMiddleware(compiler))app.get("/", function(req, res) {res.sendFile(__dirname + '/index.html')
})app.listen(port, function(error) {if (error) {console.error(error)} else {console.info("==> ��  Listening on port %s. Open up http://localhost:%s/ in your browser.", port, port)}
})

webpack.config.js

var path = require('path')
var webpack = require('webpack')module.exports = {devtool: 'cheap-module-eval-source-map',entry: ['webpack-hot-middleware/client','./index'],output: {path: path.join(__dirname, 'dist'),filename: 'bundle.js',publicPath: '/static/'},plugins: [new webpack.optimize.OccurenceOrderPlugin(),new webpack.HotModuleReplacementPlugin(),new webpack.NoErrorsPlugin()],module: {loaders: [{test: /\.js$/,loaders: [ 'babel' ],exclude: /node_modules/,include: __dirname}]}
}

npm start 后执行node server ,触发webpack。webpack插件功能如下:

OccurenceOrderPlugin的作用是给经常使用的模块分配最小长度的id。
HotModuleReplacementPlugin是热替换,热替换和dev-server的hot有什么区别?不用刷新页面,可用于生产环境。
NoErrorsPlugin用于保证编译后的代码永远是对的,因为不对的话会自动停掉。
webpackHotMiddleware

server.js中webpackHotMiddleware的用法是参考官网的,没有为什么,express中间件就是在请求后执行某些操作。

教程源代码及目录
https://github.com/lewis617/react-redux-tutorial

这篇关于react+redux教程(一)connect、applyMiddleware、thunk、webpackHotMiddleware的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1016012

相关文章

vite搭建vue3项目的搭建步骤

《vite搭建vue3项目的搭建步骤》本文主要介绍了vite搭建vue3项目的搭建步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学... 目录1.确保Nodejs环境2.使用vite-cli工具3.进入项目安装依赖1.确保Nodejs环境

Nginx搭建前端本地预览环境的完整步骤教学

《Nginx搭建前端本地预览环境的完整步骤教学》这篇文章主要为大家详细介绍了Nginx搭建前端本地预览环境的完整步骤教学,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录项目目录结构核心配置文件:nginx.conf脚本化操作:nginx.shnpm 脚本集成总结:对前端的意义很多

前端缓存策略的自解方案全解析

《前端缓存策略的自解方案全解析》缓存从来都是前端的一个痛点,很多前端搞不清楚缓存到底是何物,:本文主要介绍前端缓存的自解方案,文中通过代码介绍的非常详细,需要的朋友可以参考下... 目录一、为什么“清缓存”成了技术圈的梗二、先给缓存“把个脉”:浏览器到底缓存了谁?三、设计思路:把“发版”做成“自愈”四、代码

通过React实现页面的无限滚动效果

《通过React实现页面的无限滚动效果》今天我们来聊聊无限滚动这个现代Web开发中不可或缺的技术,无论你是刷微博、逛知乎还是看脚本,无限滚动都已经渗透到我们日常的浏览体验中,那么,如何优雅地实现它呢?... 目录1. 早期的解决方案2. 交叉观察者:IntersectionObserver2.1 Inter

Vue3视频播放组件 vue3-video-play使用方式

《Vue3视频播放组件vue3-video-play使用方式》vue3-video-play是Vue3的视频播放组件,基于原生video标签开发,支持MP4和HLS流,提供全局/局部引入方式,可监听... 目录一、安装二、全局引入三、局部引入四、基本使用五、事件监听六、播放 HLS 流七、更多功能总结在 v

全网最全Tomcat完全卸载重装教程小结

《全网最全Tomcat完全卸载重装教程小结》windows系统卸载Tomcat重新通过ZIP方式安装Tomcat,优点是灵活可控,适合开发者自定义配置,手动配置环境变量后,可通过命令行快速启动和管理... 目录一、完全卸载Tomcat1. 停止Tomcat服务2. 通过控制面板卸载3. 手动删除残留文件4.

Python的pandas库基础知识超详细教程

《Python的pandas库基础知识超详细教程》Pandas是Python数据处理核心库,提供Series和DataFrame结构,支持CSV/Excel/SQL等数据源导入及清洗、合并、统计等功能... 目录一、配置环境二、序列和数据表2.1 初始化2.2  获取数值2.3 获取索引2.4 索引取内容2

JS纯前端实现浏览器语音播报、朗读功能的完整代码

《JS纯前端实现浏览器语音播报、朗读功能的完整代码》在现代互联网的发展中,语音技术正逐渐成为改变用户体验的重要一环,下面:本文主要介绍JS纯前端实现浏览器语音播报、朗读功能的相关资料,文中通过代码... 目录一、朗读单条文本:① 语音自选参数,按钮控制语音:② 效果图:二、朗读多条文本:① 语音有默认值:②

vue监听属性watch的用法及使用场景详解

《vue监听属性watch的用法及使用场景详解》watch是vue中常用的监听器,它主要用于侦听数据的变化,在数据发生变化的时候执行一些操作,:本文主要介绍vue监听属性watch的用法及使用场景... 目录1. 监听属性 watch2. 常规用法3. 监听对象和route变化4. 使用场景附Watch 的

前端导出Excel文件出现乱码或文件损坏问题的解决办法

《前端导出Excel文件出现乱码或文件损坏问题的解决办法》在现代网页应用程序中,前端有时需要与后端进行数据交互,包括下载文件,:本文主要介绍前端导出Excel文件出现乱码或文件损坏问题的解决办法,... 目录1. 检查后端返回的数据格式2. 前端正确处理二进制数据方案 1:直接下载(推荐)方案 2:手动构造