草珊瑚的redux使用方式
前言
阮大师写入门教程能力一流。
首推它的Redux三篇入门文章。
http://www.ruanyifeng.com/blog/2016/09/redux_tutorial_part_one_basic_usages.html
http://www.ruanyifeng.com/blog/2016/09/redux_tutorial_part_two_async_operations.html
http://www.ruanyifeng.com/blog/2016/09/redux_tutorial_part_three_react-redux.html
这三篇文章介绍了,
Redux的基本概念和API,异步操作,以及如何跟React相结合。
文章写得不错,但实践起来还是略显繁琐。
思考
下面提出我自己对Redux结合React使用的思考。
使用ramda库组合自定义中间件。
这使得代码更灵活和透明。异步操作也结合ramda库。
可以不用引入第三方redux-thunk,redux-promise中间件。
使用ramda库更方便组合异步操作。state以React组件的state为准。
redux的state只是辅助计算出React组件的state。往store注入trigger函数,用来setState更新React组件。
在线demo
示例代码如下:
index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
</head>
<body>
<h1>Hello world</h1>
<div id="app"></div>
<script src="index.js"></script>
</body>
</html>
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import store from './store.js';
import {connect} from './connect.js';
class Test extends React.Component {
constructor(props) {
super(props);
this.state = {
value:0,
otherNum:0,
asyncing:false
};
}
dispatch(obj){
obj.state= this.state;
store.dispatch(obj);
}
setOtherData(){
this.dispatch({ type: 'Other' });
}
setData(){
this.dispatch({ type: 'INCREMENT' });
}
async(){
this.dispatch({type: 'Loading' });
this.dispatch({ type: 'ASYNC'});
}
componentDidMount(){
//store.dispatch({type: 'Init'})
}
render() {
const t = this;
console.log('render', store.getState(), t.state);
const {value ,asyncing,otherNum } = t.state;
return (
<div>
<div>数字:{value}</div>
<div onClick={t.setData.bind(this)}>点我+1</div>
{
(()=>{
if(asyncing){
return (<div>异步加载中</div>);
}
else{
return (<div onClick={t.async.bind(t)}>点我异步+10</div>);
}
})()
}
<br />
<div onClick={t.setOtherData.bind(this)}>点我其他数字+1</div>
<div>其他数字:{otherNum}</div>
</div>);
}
}
const NewTest = connect(store)(Test) ;
ReactDOM.render(
<NewTest />,
document.getElementById('app')
)
module.exports = NewTest;
store.js
import { createStore } from 'redux';
import R from 'ramda';
const isPromise = function(e){
return !!e&&typeof e.then=="function";
};
const setTimeout1 = R.curry(function( state ){
return new Promise(function(resolve, reject){
setTimeout(function(){
resolve(state+ 10);
},1000);
})
});
// reducer,仅用于计算。
function counter(state = {}, action) {
if(isPromise(state)){
state = {};
}
state = R.merge(state, action.state);
console.log('reducer中的state',state);
switch (action.type) {
case 'Init':
return action.state;
case 'INCREMENT':
state.value = state.value + 1;
return state
case 'ASYNC':
return R.composeP( setTimeout1)(state.value);
case 'Loading':
return {asyncing: true}
case 'Other':
return {otherNum: state.otherNum+1};
default:
return state
}
}
let store = createStore(counter);
// subscribe,可用于执行含有副作用的操作。
store.subscribe((e) =>{
console.log('subscribe',store, store.getState(),e, this);
let state = store.getState();
if(isPromise(state)){
state.then(function(num){
store.trigger({value: num, asyncing:false });
})
}
else{
store.trigger(store.getState());
}
})
module.exports = store;
connect.js
import {type} from 'ramda';
exports.connect = function (listenable, context) {
if(type(listenable) !== 'Object'){
throw new Error('connect function\'s argument is not a object');
}
listenable.trigger = function (obj,fn) {
this.setState(obj || {}, fn);
};
listenable.getReactState = function(){
return this.state;
};
return function(otherReactClass){
return class baseReactClass extends otherReactClass {
constructor(){
super();
}
componentDidMount(...args) {
context = context || this;
listenable.trigger = listenable.trigger.bind(context);
listenable.getReactState = listenable.getReactState.bind(context);
super.componentDidMount();
}
componentWillUnmount() {
listenable.trigger = null;
super.componentWillUnmount();
}
}
}
}
草珊瑚的redux使用方式的更多相关文章
- 翻译 | Thingking in Redux(如果你只了解MVC)
作者:珂珂(沪江前端开发工程师) 本文原创,转载请注明作者及出处. 原文地址:https://hackernoon.com/thinking-in-redux-when-all-youve-known ...
- redux 与 react-redux
Redux 一.Redux 三大原则: 1.一个应用永远只有一个数据源(整个应用状态都保存在一个对象中,Redux提供的工具函数combineReducers可以解决庞大的数据对象的问题) 2.状态是 ...
- 我所遭遇过的游戏中间件---Redux
我所遭遇过的游戏中间件---Redux 一.关于Redux Substance Redux 是一款纹理处理软件加中间件,专门用于纹理生成和压缩.具其用户指南介绍,它能够对纹理集进行优化,可以将现有压缩 ...
- redux详解
redux介绍 学习文档:英文文档,中文文档,Github redux是什么 redux是一个独立专门用于做状态管理的JS库(不是react插件库),它可以用在react, angular, vue等 ...
- 前端AntD框架的upload组件上传图片时遇到的一些坑
前言 本次做后台管理系统,采用的是 AntD 框架.涉及到图片的上传,用的是AntD的 upload 组件. 前端做文件上传这个功能,是很有技术难度的.既然框架给我们提供好了,那就直接用呗.结果用的时 ...
- React+DvaJS 之 hook 路由权限控制
博客 学院 下载 GitChat TinyMind 论坛 APP 问答 商城 VIP 活动 招聘 ITeye 写博客 发Chat 登录注册 原 React+DvaJS 之 hook 路由权限控制 20 ...
- react的状态管理
近两年前端技术的发展如火如荼,大量的前端项目都在使用或转向 Vue 和 React 的阵营, 由前端渲染页面的单页应用占比也越来越高,这就代表前端工作的复杂度也在直线上升,前端页面上展示的信息越来越多 ...
- react之传递数据的几种方式props传值、路由传值、状态提升、redux、context
react之传递数据的几种方式 1.父子传值 父传值:<子的标签 value={'aaa'} index={'bbb'}></子的标签> 子接值:<li key={thi ...
- 使用redux代码文件的组织方式
从架构触发,开始一个新应用的时候,代码文件的组织方式一定要考虑好 如果之前使用过mvc的框架那么对按角色组织方式一定不陌生 角色组织方式 reducer/ todoReducer.js filterR ...
随机推荐
- flask 表单
表单 在Web程序中,表单时和用户交互最常见的方式之一.用户注册.登录.撰写文章.编辑设置,无一不用到表单.不过,表单的处理不简单.要创建表单,验证用户输入的内容,向用户显示错误提示,还要获取并保存数 ...
- Python数据类型深入学习之数字
一. 数字常量 1. 下面来看看Python的数字常量中都要哪些类型: 数字 常量 129,-89,0 一般整数 9999848499999L,4594646469l 长整型数(无限大小) 1.232 ...
- 单台主机上DB2 10.5和arcgis 10.4 空间数据库配置
该篇文章重点参考arcgis官网说明:http://enterprise.arcgis.com/zh-cn/server/10.4/publish-services/linux/register-db ...
- tomcat2章1
package ex02.pyrmont; import java.io.File; public class Constants { public static final String WEB_R ...
- OSI七层详解
OSI 七层模型通过七个层次化的结构模型使不同的系统不同的网络之间实现可靠的通讯,因此其最主要的功能就是帮助不同类型的主机实现数据传输 . 完成中继功能的节点通常称为中继系统.在OSI七层模型中,处于 ...
- Service_name 和Sid的区别
Service_name:该参数是由oracle8i引进的.在8i以前,使用SID来表示标识数据库的一个实例,但是在Oracle的并行环境中,一个数据库对应多个实例,这样就需要多个网络服务名,设置繁琐 ...
- 【javascript】对原型对象、原型链的理解
原型对象,原型链这些知识属于基础类知识.但是平时开发过程中也很少用到. 看网上的意思,原型链用于es5开发场景下的继承.es6有了类语法糖之后,就自带继承了. 通过理解,个人画了一张原型链解构的关系图 ...
- P3690 【模板】Link Cut Tree (动态树)
P3690 [模板]Link Cut Tree (动态树) 认父不认子的lct 注意:不 要 把 $fa[x]$和$nrt(x)$ 混 在 一 起 ! #include<cstdio> v ...
- 使ipconfig命令结果更整洁
在windows下,使用ipconfig命令会出来很多内容,很多事ipv6隧道适配器的内容.而现在大部分人都还用不到ipv6,因此我们可以输入以下命令关闭ipv6隧道适配器,使命令结果更整洁. net ...
- 深入理解 Vue 组件
深入理解 Vue 组件 组件使用中的细节点 使用 is 属性,解决组件使用中的bug问题 <!DOCTYPE html> <html lang="en"> ...