本教程总共6篇,每日更新一篇,请关注我们!你可以进入历史消息查看以往文章,也敬请期待我们的新文章!
1、React第三方组件5(状态管理之Redux的使用①简单使用)---2018.03.20
2、React第三方组件5(状态管理之Redux的使用②TodoList上)---2018.03.21
3、React第三方组件5(状态管理之Redux的使用③TodoList中)---2018.03.22
4、React第三方组件5(状态管理之Redux的使用④TodoList下)---2018.03.23
5、React第三方组件5(状态管理之Redux的使用⑤异步操作)---2018.03.26
6、React第三方组件5(状态管理之Redux的使用⑥Redux DevTools)---2018.03.27
开发环境:Windows 8,node v8.9.1,npm 5.5.1,WebStorm 2017.2.2
1、我们复制一份redux3到redux4中,并修改redux下Index.jsx
2、修改 redux4下Index.jsx文件
import React from 'react'; import {createStore} from 'redux'; import {Provider, connect} from 'react-redux'; import reducer from './reducer' import List from './List' const store = createStore(reducer); class Index extends React.Component { render() { let props = this.props; return ( <div className="todoList"> <input type="text" ref="todoInput"/> <button onClick={() => this.props.dispatch({type: 'ADD', title: this.refs['todoInput'].value})}>添加 </button> <div className="cont"> <div className="box"> 全部 <List type={0} {...props}/> </div> <div className="box"> 未删除 <List type={1} {...props}/> </div> <div className="box"> 已删除 <List type={2} {...props}/> </div> </div> </div> ); } } const mapStateToProps = state => ({storeState: state}); const Main = connect( mapStateToProps )(Index); export default () => <Provider store={store}> <Main/> </Provider> ;
3、新建LIst.jsx文件
import React from 'react'; class List extends React.Component { render() { let {list} = this.props.storeState; let type = this.props.type; let LiCont = ({data}) => <li> {data.title} <button onClick={() => this.props.dispatch({ type: 'EDIT', obj: { id: data.id, status: data.status === 1 ? 0 : 1 } })} className={data.status === 1 ? "del" : "recovery"}> {data.status === 1 ? "删除" : "恢复"} </button> </li> ; return ( <div className="list"> { list.length > 0 && list.map(data => [ type === 0 ? <LiCont data={data} key={data.id}/> : type === 1 && data.status === 1 ? <LiCont data={data} key={data.id}/> : type === 2 && data.status === 0 ? <LiCont data={data} key={data.id}/> : null ] ) } </div> ); } } export default List;
4、reducer.js
export default (state = { list: [] }, action) => { let list = state.list; switch (action.type) { case 'ADD': if (!action.title) { alert('不能为空'); return state; } list.push({id: state.list.length + 1, title: action.title, status: 1}); return {list}; case 'EDIT': let {id,status} = action.obj; list.find(data => data.id === id).status = status; return {list}; default: return state; } };
5、查看浏览器
本文完
禁止擅自转载,如需转载请在公众号中留言联系我们!
感谢童鞋们支持!
如果你有什么问题,可以在下方留言给我们!