React-redux实现小案例(todolist)的过程
why_Because 人气:0使用React-redux实现,待办事项todolist案例。
注:以下列出主要页面代码,为说明React-redux实现的过程,所以并没有将案例的完整代码展示!
一、全局安装:rudux、react-redux
npm install redux --save npm install react-redux
二、主要代码:
1、项目的入口文件index.js
import React from 'react'; import ReactDOM from 'react-dom'; import './style/main.less'; import App from './App'; import * as serviceWorker from './serviceWorker'; //*********** 引入容器组件 ************* import {Provider} from 'react-redux'; import store from './store/store'; ReactDOM.render( // ********* 套入Provider组件,传入store ********* <Provider store={store}> <App /> </Provider> , document.getElementById('root')); serviceWorker.unregister();
2、列表页面(删除、完成)
import React from 'react'; import actionCreator from '../../../store/todoStore/actionCreator' ; import {connect} from 'react-redux'; import { bindActionCreators } from 'redux'; class TodoEvent extends React.Component{ //删除 delete(id){ // alert('delete'+id) this.props.delete(id); } //完成 finish(id){ // alert('finish'+id) this.props.finish(id); } //渲染函数 renderList(){ //容器组件,通过props获取 let {todolist}=this.props.todoStore; return todolist.map((item)=>{ return <li className='list-group-item' key={item.id}> {item.title} <button onClick={this.delete.bind(this,item.id)} className='btn btn-danger'>删除</button> {item.isFinish?'已完成': <button onClick={this.finish.bind(this,item.id)} className='btn btn-success'>完成</button>} </li> }) } //渲染页面 render(){ return( <div> <ul className='list-group'> {this.renderList()} </ul> </div> ) } } let mapStateToProps=(state)=>{ return state; } //bindActionCreators 将绑定的actionCreator中的方法,放到props里直接调用,并触发dispacth let mapDispatchToProps=(dispatch)=>{ return bindActionCreators(actionCreator,dispatch) } //通过connect将UI组件,转换成容器组件 export default connect(mapStateToProps,mapDispatchToProps)(TodoEvent) //简写,将 mapStateToProps 和 mapDispatchToProps 直接引入 connect // export default connect(state=>state,(dispatch)=>{ // return bindActionCreators(actionCreator,dispatch) // })(TodoEvent)
3、actionCreator组件
//actionCreator中对应的方法,只需 return action const actionCreator={ addlist(title){ let action={ type:'ADD_LIST', title:title } return action }, delete(id){ let action={ type:'DELETE_LIST', id:id } return action }, finish(id){ let action={ type:'FINISH_LIST', id:id } return action } } export default actionCreator
加载全部内容