本教程总共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
关于Redux的相关知识,请查阅阮老师的博客:
Redux 入门教程(一):基本用法 http://www.ruanyifeng.com/blog/2016/09/redux_tutorial_part_one_basic_usages.html
Redux 入门教程(二):中间件与异步操作 http://www.ruanyifeng.com/blog/2016/09/redux_tutorial_part_two_async_operations.html
Redux 入门教程(三):React-Redux 的用法 http://www.ruanyifeng.com/blog/2016/09/redux_tutorial_part_three_react-redux.html
我这里就不对这些概念多做介绍!
我们上来直接撸码!
安装 redux react-redux
npm i -S redux react-redux
1、在demo目录下新建redux文件夹,并建立redux1文件夹
2、在redux下新建Index.jsx
import React from 'react'; import {HashRouter, Route, NavLink, Redirect} from 'react-router-dom'; import Redux1 from './redux1/Index' const Index = ({match}) => <HashRouter> <div> <div className="nav"> <NavLink to="/Redux/Redux1" activeClassName="selected">Redux1</NavLink> </div> <Route exact path={`${match.url}`} render={() => (<Redirect to={`${match.url}/Redux1`}/>)}/> <Route path={`${match.url}/Redux1`} component={Redux1}/> </div> </HashRouter> ; export default Index;
3、修改demo下Index.jsx
4、在redux1下建立 Index.jsx文件
import React from 'react'; class Index extends React.Component { constructor(props) { super(props); this.state = {}; } componentDidMount() { } render() { return ( <div> redux </div> ); } } export default Index;
5、打开浏览器,应该是下图这样的
6、写业务代码
<div> 0 <button>+</button> </div>
我们希望点击按钮,数字可以加1
7、我们新建reducer.js
export default (state = { num: 0 }, action)=> { switch (action.type) { case 'ADD': return {num:state.num + action.num}; default: return state; } };
8、修改Index.jsx
import React from 'react'; import {createStore} from 'redux'; import {Provider, connect} from 'react-redux'; import reducer from './reducer' const store = createStore(reducer); class Index extends React.Component { render() { return ( <div> {this.props.storeState.num} <button onClick={() => this.props.dispatch({type: 'ADD', num: 1})}>+</button> </div> ); } } const mapStateToProps = state => ({storeState: state}); const Main = connect( mapStateToProps )(Index); export default () => <Provider store={store}> <Main/> </Provider> ;
9、查看浏览器
本文完
禁止擅自转载,如需转载请在公众号中留言联系我们!
感谢童鞋们支持!
如果你有什么问题,可以在下方留言给我们!
来源:React第三方组件5(状态管理之Redux的使用①简单使用)-留客客-获客营销saas系统