redux、react-redux、redux-thunk、redux-saga使用及dva对比
一、redux使用
1、src下新建store文件夹,新建index.js作为store的输出文件
2、store文件夹下新建index.js文件
3、新建reducer.js ,actionTypes.js文件

4、组件引入store
import React, { Component } from 'react';
import { Input ,Button,List } from 'antd';
import store from './store';
import {CHANGE_INPUT_VALUE,ADD_TODO_ITEM,DELETE_TODO_ITEM} from './store/actionTypes'
class TodoList extends Component {
constructor(props) {
super(props);
this.state = store.getState();
this.handleStoreChange = this.handleStoreChange.bind(this);
this.handleBtnClick = this.handleBtnClick.bind(this);
this.handleInputChange = this.handleInputChange.bind(this);
store.subscribe(this.handleStoreChange)
}
handleInputChange(e) {
const action = {
type: CHANGE_INPUT_VALUE,
value: e.target.value
}
store.dispatch(action)
}
handleBtnClick() {
const action = {
type: ADD_TODO_ITEM
}
store.dispatch(action)
}
render() {
return (
<div style={{marginTop:'20px',marginLeft:'15px'}}>
<div>
<Input
value={this.state.inputValue}
placeholder="input"
style={{width:'300px'}}
onChange={this.handleInputChange}
/>
<Button onClick={this.handleBtnClick} type="primary">Primary</Button>
</div>
<List
style={{marginTop:'15px',width:'300px'}}
bordered
dataSource={this.state.list}
renderItem={(item,index) => <List.Item onClick={this.handleItemDelete.bind(this,index)}>{item}</List.Item>}
/>
</div>
)
}
handleStoreChange() {
this.setState(store.getState())
}
handleItemDelete(index) {
const action = {
type: DELETE_TODO_ITEM,
index
}
store.dispatch(action)
}
}
export default TodoList;
5、使用redux-devtool
import { createStore } from 'redux';
import reducer from './reducer'
const store = createStore(
reducer,
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);
export default store;
6、actionTypes.js代码如下
export const CHANGE_INPUT_VALUE = 'change_input_value';
export const ADD_TODO_ITEM = 'add_todo_item';
export const DELETE_TODO_ITEM = 'delete_todo_item';
7、reducer.js代码如下
import {CHANGE_INPUT_VALUE,ADD_TODO_ITEM,DELETE_TODO_ITEM} from './actionTypes'
const defaultState = {
inputValue:'aaa',
list:['1','2']
}
export default (state = defaultState,action) => {
if(action.type === CHANGE_INPUT_VALUE) {
const newState = JSON.parse(JSON.stringify(state));
newState.inputValue = action.value;
return newState;
}
if(action.type === ADD_TODO_ITEM) {
const newState = JSON.parse(JSON.stringify(state));
newState.list.push(newState.inputValue);
newState.inputValue = '';
return newState;
}
if(action.type === DELETE_TODO_ITEM) {
const newState = JSON.parse(JSON.stringify(state));
newState.list.splice(action.index,1);
return newState;
}
return state;
}
8、优化:使用actionCreactor.js来统一管理action

二、引入react-redux
1.在index.js里引入react-redux及store
import React from 'react';
import ReactDOM from 'react-dom';
import 'antd/dist/antd.css';
import './index.css';
import App from './TodoList';
import * as serviceWorker from './serviceWorker';
import store from './store'
import { Provider } from 'react-redux'; const ProviderApp = (
<Provider store={store}>
<App></App>
</Provider>
) ReactDOM.render(ProviderApp, document.getElementById('root'));
serviceWorker.unregister();
2.在组件里做connect
import React, { Component } from 'react';
import { Input ,Button,List } from 'antd';
import {CHANGE_INPUT_VALUE,ADD_TODO_ITEM} from './store/actionTypes'
import {connect} from 'react-redux';
class TodoList extends Component {
render() {
const {handleInputChange,handleBtnClick} = this.props
return (
<div style={{marginTop:'20px',marginLeft:'15px'}}>
<div>
<Input
value={this.props.inputValue}
placeholder="input"
style={{width:'300px'}}
onChange={handleInputChange}
/>
<Button onClick={handleBtnClick} type="primary">Primary</Button>
</div>
<List
style={{marginTop:'15px',width:'300px'}}
bordered
dataSource={this.props.list}
renderItem={(item,index) => <List.Item>{item}</List.Item>}
/>
</div>
)
}
}
const mapStateToProps = (state) => {
return {
inputValue: state.inputValue,
list : state.list
}
}
const mapDispatchToProps = (dispatch) => {
return {
handleInputChange(e) {
const action = {
type: CHANGE_INPUT_VALUE,
value: e.target.value
}
dispatch(action)
},
handleBtnClick() {
const action = {
type: ADD_TODO_ITEM
}
dispatch(action)
},
}
}
export default connect(mapStateToProps,mapDispatchToProps)(TodoList);
三、redux-thunk使用
1.中间件的概念
dispatch一个action之后,到达reducer之前,进行一些额外的操作,就需要用到middleware。你可以利用 Redux middleware 来进行日志记录、创建崩溃报告、调用异步接口或者路由等等。
换言之,中间件都是对store.dispatch()的增强。redux-thunk就是用来异步操作,比如接口请求等。
2.引入redux-thunk
import { applyMiddleware, createStore } from 'redux';
import thunk from 'redux-thunk';
const store = createStore(
reducers,
applyMiddleware(thunk)
);
3.这样就可以再actionCreactor中创建一个带异步函数的方法了
export const getTodoList = () => {
return () => {
axios.get('./list').then((res)=>{
const data = res.data;
const action = initListAction(data);
StorageEvent.dispatch(action);
})
}
}
四、redux-saga使用
redux-saga是一个用于管理redux应用异步操作的中间件,redux-saga通过创建sagas将所有异步操作逻辑收集在一个地方集中处理,可以用来代替redux-thunk中间件。
1.在store.js里引入redux-saga
import { createStore, applyMiddleware } from 'redux'
import createSagaMiddleware from 'redux-saga'
import reducer from './reducers'
import mySaga from './sagas'
// create the saga middleware
const sagaMiddleware = createSagaMiddleware()
// mount it on the Store
const store = createStore(
reducer,
applyMiddleware(sagaMiddleware)
)
// then run the saga
sagaMiddleware.run(mySaga);
export default store;
2.新建 saga.js
import { call, put, takeEvery, takeLatest } from 'redux-saga/effects'
import Api from '...'
// worker Saga: will be fired on USER_FETCH_REQUESTED actions
function* fetchUser(action) {
try {
const user = yield call(Api.fetchUser, action.payload.userId);
yield put({type: "USER_FETCH_SUCCEEDED", user: user});
} catch (e) {
yield put({type: "USER_FETCH_FAILED", message: e.message});
}
}
function* mySaga() {
yield takeEvery("USER_FETCH_REQUESTED", fetchUser);
}
export default mySaga;
五、dva对比
dva使用可以参考这个博客:https://www.cnblogs.com/superSmile/p/9972344.html
redux、react-redux、redux-thunk、redux-saga使用及dva对比的更多相关文章
- Redux React & Online Video Tutorials
Redux React & Online Video Tutorials https://scrimba.com/@xgqfrms https://scrimba.com/c/cEwvKNud ...
- 如何优雅地在React项目中使用Redux
前言 或许你当前的项目还没有到应用Redux的程度,但提前了解一下也没有坏处,本文不会安利大家使用Redux 概念 首先我们会用到哪些框架和工具呢? React UI框架 Redux 状态管理工具,与 ...
- 在 React Native 中使用 Redux 架构
前言 Redux 架构是 Flux 架构的一个变形,相对于 Flux,Redux 的复杂性相对较低,而且最为巧妙的是 React 应用可以看成由一个根组件连接着许多大大小小的组件的应用,Redux 也 ...
- React深入 - 手写redux api
简介: 手写实现redux基础api createStore( )和store相关方法 api回顾: createStore(reducer, [preloadedState], enhancer) ...
- 优雅的在React项目中使用Redux
概念 首先我们会用到哪些框架和工具呢? React UI框架 Redux 状态管理工具,与React没有任何关系,其他UI框架也可以使用Redux react-redux React插件,作用:方便在 ...
- RxJS + Redux + React = Amazing!(译一)
今天,我将Youtube上的<RxJS + Redux + React = Amazing!>翻译(+机译)了下来,以供国内的同学学习,英文听力好的同学可以直接看原版视频: https:/ ...
- RxJS + Redux + React = Amazing!(译二)
今天,我将Youtube上的<RxJS + Redux + React = Amazing!>的后半部分翻译(+机译)了下来,以供国内的同学学习,英文听力好的同学可以直接看原版视频: ht ...
- react+redux教程(二)redux的单一状态树完全替代了react的状态机?
上篇react+redux教程,我们讲解了官方计数器的代码实现,react+redux教程(一).我们发现我们没有用到react组件本身的state,而是通过props来导入数据和操作的. 我们知道r ...
- [Redux] React Todo List Example (Toggling a Todo)
/** * A reducer for a single todo * @param state * @param action * @returns {*} */ const todo = ( st ...
随机推荐
- Win10《芒果TV》商店版双十一独家大礼,每日前100名用户免费领取7天VIP
为答谢大家对Win10<芒果TV>商店版一年以来一如既往的支持,2016年11月1日-11月30日期间,每天登录<芒果TV>UWP版(最新版本v3.1.3)的前100位用户可领 ...
- WPF 用Main函数方式启动程序
原文:WPF 用Main函数方式启动程序 WPF默认程序启动:新建project后自动生成的App.xaml中指定程序启动方式(StartupUri="MainWindow.xaml&quo ...
- 基于CKEditor 你能做很多App。CKEditor 4.5 and CKFinder 3 beta 发布
直击现场 CKEditor 4.5 and CKFinder 3 beta 发布 oschina 发布于: 2015年04月10日 (0评) 分享到: 收藏 +5 4月18日 武汉 源创会开始报 ...
- SpringCloud微服务架构升级总结
一.背景 1.1 应用系统的架构历史 1.2 什么是微服务? 起源:微服务的概念源于 2014 年 3 月 Martin Fowler 所写的一篇文章“Microservices”.文中内容提到:微服 ...
- Hystrix断路器配置属性解析
HystrixCommand 配置方式 我们的配置都是基于 HystrixCommand 的,我们通过在方法上添加 @HystrixCommand 注解并配置注解的参数来实现配置,但有的时候一个类里面 ...
- Python字典的合并与拆分
1.字典的合并 dict1={1:[1,11,111],2:[2,22,222]} dict2={3:[3,33,333],4:[4,44,444]} dictMerged2=dict(dict1, ...
- WebApp 安全风险与防护课堂(第二讲)开课了!
本文由葡萄城技术团队于原创并首发 转载请注明出处:葡萄城官网,葡萄城为开发者提供专业的开发工具.解决方案和服务,赋能开发者. 在昨天的公开课中,由于参与的小伙伴们积极性和热情非常高,我们的讲师Carl ...
- Python基础,day1
一. Python介绍 目前Python主要应用领域: 云计算: 云计算最火的语言, 典型应用OpenStack WEB开发: 众多优秀的WEB框架,众多大型网站均为Python开发,Youtube, ...
- vue 左右滑动效果
个人实际开发中用到的效果问题总结出来便于自己以后开发查看调用,如果也适用其他人请随意拿走勿喷就行! vue.js是现在流行的js框架之一,vue 是一套用于构建用户界面的渐进式javascript框架 ...
- 12 DOM操作的相关案例
1.模态框案例 需求: 打开网页时有一个普通的按钮,点击当前按钮显示一个背景图,中心并弹出一个弹出框,点击X的时候会关闭当前的模态框 代码如下: <!DOCTYPE html> <h ...