最简单的React和Redux整合的例子

安装create-react-app
npm install -g create-react-app


创建项目
create-react-app reactreduxrouterdemo
cd reactreduxrouterdemo
安装第三方模块
npm install --save redux
npm install --save react-redux
npm install --save react-router


修改index.js

 

[javascript] view plain copy

  1. import React, { Component } from 'react';  
  2. import ReactDOM from 'react-dom';  
  3. import { createStore } from 'redux';  
  4. import { Provider, connect } from 'react-redux';  
  5.   
  6.   
  7. //定义组件  
  8. class App extends Component{  
  9.     render() {  
  10.         const {text, onChangeText, onButtonClick} = this.props;  
  11.         return (  
  12.             <div>  
  13.                 <h1 onClick={onChangeText}> {text} </h1>  
  14.                 <button onClick={onButtonClick}>click me</button>  
  15.             </div>  
  16.         );  
  17.     }  
  18. }  
  19.   
  20.   
  21. //action  
  22. const changeTextAction = {  
  23.         type:'CHANGE_TEXT'  
  24. }  
  25. const buttonClickAction = {  
  26.         type:'BUTTON_CLICK'  
  27. }  
  28.   
  29.   
  30. //reducer  
  31. const initialState = {  
  32.     text: 'Hello'  
  33. }  
  34. const reducer = (state = initialState, action) => {  
  35.     switch (action.type) {  
  36.         case 'CHANGE_TEXT':  
  37.             return {  
  38.                 text: state.text=='Hello' ? 'world':'Hello'  
  39.             }  
  40.         case 'BUTTON_CLICK':  
  41.             return {  
  42.                 text: 'Hello world'  
  43.             }  
  44.         default:  
  45.             return initialState;  
  46.     }  
  47. }  
  48.   
  49. //store  
  50. let store = createStore(reducer);  
  51.   
  52. //映射Redux state到组件的属性  
  53. function mapStateToProps(state) {  
  54.     return { text: state.text }  
  55. }  
  56.   
  57. //映射Redux actions到组件的属性  
  58. function mapDispatchToProps(dispatch){  
  59.     return{  
  60.         onButtonClick:()=>dispatch(buttonClickAction),  
  61.         onChangeText:()=>dispatch(changeTextAction)  
  62.     }  
  63. }  
  64.   
  65. //连接组件  
  66. App = connect(mapStateToProps, mapDispatchToProps)(App)  
  67.   
  68. //渲染组件  
  69. ReactDOM.render(  
  70.     <Provider store={store}>  
  71.         <App />  
  72.     </Provider>,  
  73.     document.getElementById('root')  
  74. )  









这个例子大概是最简单的了, 而且每一步注释都非常清楚了。
运行工程npm start






源代码工程
https://github.com/chenhaifeng2016/reactreduxrouter

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值