react-redux进阶
一、 安装:
npm install redux react-redux
二、入口文件:index.jsx:
- 引入:
- 创建reducer:
- 创建容器:
- 初始化:
- 将容器绑定到属性:
- 完整代码:
// 核心 var React = require('react') var ReactDom = require('react-dom') var CreateClass = require('create-react-class') var createStore = require('redux').createStore var Provider = require('react-redux').Provider var ReduxFactory = require('dollarphp-redux-factory') // 引入组件 var App = require('./static/jsx/app.jsx') var Item = App.Item var Text = App.Text // 创建容器 var reducer_item = ReduxFactory var reducer_text = ReduxFactory var item = createStore(reducer_item) var text = createStore(reducer_text) // 创建组件 var Index = CreateClass({ componentWillMount :function(){ item.dispatch({ type:'hello' }) text.dispatch({ type:'world' }) }, render:function(){ return (
, document.getElementById('app') ) 三、子组件:app.jsx:
- 引入:
- 定义处理函数:
- 定义执行事件:
- 导出:
- 完整代码:
// 核心 var React = require('react') var ReactDom = require('react-dom') var CreateClass = require('create-react-class') var connect = require('react-redux').connect // 创建组件 var Item = CreateClass({ todo:function(){ var type = 'item' this.props.dispatch({ type:type }) }, render:function(){ return (
值:{this.props.state}) } }) var Text = CreateClass({ todo:function(){ var type = 'text' this.props.dispatch({ type:type }) }, render:function(){ return (值:{this.props.state}) } }) var Item = connect(function(state){ return { state:state } })(Item) var Text = connect(function(state){ return { state:state } })(Text) var App = { Item:Item, Text:Text } module.exports = App四、效果:
- 初始状态:
- 点击item:
- 点击text:
五、补充:
- 引入:
var CreateStore = require('redux').createStore var CombineReducers = require('redux').combineReducers var Provider = require('react-redux').Provider
成都创新互联公司长期为成百上千家客户提供的网站建设服务,团队从业经验10年,关注不同地域、不同群体,并针对不同对象提供差异化的产品和服务;打造开放共赢平台,与合作伙伴共同营造健康的互联网生态环境。为盐边企业提供专业的网站制作、成都网站制作,盐边网站改版等技术服务。拥有10年丰富建站经验和众多成功案例,为您定制开发。
- 创建容器:
var api = function(state = 'http://api.dollarphp.com/',action){ var type = action.type if(type == 'background'){ state += 'blog/login/background' }else if(type == "login"){ state += 'blog/login/login' } return state } var progress = function( state = { percent:0, prompt:'', display:'block' }, action ){ var type = action.type if(type == 'progress'){ state.percent = action.percent state.prompt = action.prompt if(action.percent == 100){ state.display = 'none' } } return state }
- 合并:
var store = CombineReducers({ api, progress }) store = CreateStore(store)
- 初始化容器内容:
store.dispatch({ type:"percent", percent:100, prompt:'test' })
- 添加到组件:
标题名称:react-redux进阶
浏览路径:http://ybzwz.com/article/igcheo.html