1 安装react-redux: npm install --save react-redux

2.之前使用redux的store.subscribe监听 store的状态改变,通过store.getState函数获取store的状态值;并且需要划分ui组件和聪明组件,着实很麻烦,引入react-redux,可以改变这一切;

store定义如下,引入react-redux:

import { createStore, compose, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import reducer from './reducer'; const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(reducer, composeEnhancers(
applyMiddleware(thunk)
)); export default store;

3. 顶部组件在最外层引入store,这样所有的组件都可以使用store了;

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

4.具体在组件中使用connect将 ui组件变成聪明组件:

import React, { Component } from 'react';
import './App.css';
import { connect } from 'react-redux'
import {changeInputValue,addInputValue,deleteListItem,getListData} from './store/actionCreator.js'
class App extends Component {
constructor(props){
super(props);
this.state = {}
}
componentDidMount(){
this.props.getListDatas();
}
render() {
const {inputValue,changeInputValue,addListItem,list,deleteList} = this.props;
return (
<div className="App">
<label htmlFor="box">
输入信息
<input id="box"
value = {inputValue}
onChange ={changeInputValue}
/>
<button onClick={addListItem}>提交</button>
</label>
<ul>
{
list.map((item,index) => {
return (
<li key={index} onClick={deleteList.bind(this,index) }>{item}</li>
)
})
}
</ul>
</div>
);
} }
const mapStateToProps = (state)=> {
return (
{
inputValue:state.inputValue,
list:state.list
}
)
};
const mapDispatchToProps = (dispatch)=>{
return {
changeInputValue(e){
dispatch(changeInputValue(e.target.value))
},
addListItem(){
dispatch(addInputValue())
},
deleteList(index){
dispatch(deleteListItem(index))
},
getListDatas(){
dispatch(getListData())
}
}
}
export default connect(mapStateToProps,mapDispatchToProps)(App);

最新文章

  1. Android 学习笔记之三—— 音效的使用
  2. EI Index
  3. [Spring框架]Spring IOC的原理及详解。
  4. 【Java每日一题】20161109
  5. BZOJ3295 [Cqoi2011]动态逆序对
  6. CSS 样式的优先级
  7. RedRabbit——基于BrokerPattern服务器框架
  8. LeetCode-Group Shifted Strings
  9. Yii源码阅读笔记(十七)
  10. 【python cookbook】【数据结构与算法】10.从序列中移除重复项且保持元素间顺序不变
  11. fedora 关闭、禁止selinux
  12. 360每日自动签到,领取积分 (java httpclient4.x)
  13. Matlab---size,length和numel函数的用法
  14. PKUSC 模拟赛 day2 上午总结
  15. 【转】objective-c基本数据类型之输出格式符
  16. JanaScript预解析
  17. Android 第四次作业
  18. .Net File类的操作
  19. Java中的抽象
  20. 常见的JavaWeb安全问题及修复

热门文章

  1. jenkins部署java项目到远程linux(四)
  2. js 动态绑定鼠标事件
  3. 字符与字符串3——char 的大小
  4. Traumland--梦乡--IPA--德语
  5. 深入理解java虚拟机---Class文件(二十)
  6. Array和ArrayList有什么区别?
  7. table 奇行偶行
  8. STA/LTA方法
  9. mail.jar 发送邮件
  10. 11.Python-第三方库requests详解(三)