1. 下载依赖包
cnpm i --save redux react-redux2. action-types.js
/* * 包含所有的action type的常量字符串 */ export const INCREMENT = 'INCREMENT' export const DECREMENT = 'DECREMENT'3. actions.js
/* * 包含所有action creator */ import {DECREMENT, INCREMENT} from "./action-types"; export const increment = number => ({ type: INCREMENT, data: number }) export const decrement = number => ({ type: DECREMENT, data: number })4. redecers.js
import {DECREMENT, INCREMENT} from "./action-types"; /* * 包含多个reducer函数的模块 */ export function counter(state = 0, action) { switch (action.type) { case INCREMENT: return state + action.data case DECREMENT: return state - action.data default: return state } }5. store.js
import {createStore} from "redux"; import {counter} from './reducers' const store = createStore(counter) export default store6. App.js
import React from 'react'; import PropTypes from 'prop-types' import {decrement, increment} from "./redux/react_redux_counter/actions"; import {connect} from 'react-redux' class App extends React.Component { // 接收3个属性 static propTypes = { count: PropTypes.number.isRequired, increment: PropTypes.func.isRequired, decrement: PropTypes.func.isRequired } // 增加 increment = () => { const number = this.select.value * 1 // const {count} = this.state // this.setState({count: count + number}) // 调用store的方法更新状态 this.props.increment(number) console.log("increment", number) console.log("this.props", this.props) } // 减少 decrement = () => { const number = this.select.value * 1 // const count = this.props.store.getState() // this.setState({count: count - number}) this.props.decrement(number) } // 偶数增加(满足条件后再增加) incrementIfOdd = () => { const number = this.select.value * 1 const {count} = this.props if (count % 2 === 1) { // this.setState({count: count + number}) this.props.increment(number) } else { alert(`${count}不是奇数呦!`) } } // 异步增加(设置延时定时器) incrementAsync = () => { const number = this.select.value * 1 setTimeout(() => { this.props.increment(number) }, 1000) } render() { // const {count} = this.state // 得到原本的count状态 const {count} = this.props console.log("App", count) return ( <div> <p>click {count} times</p> <div> <select ref={select => this.select = select}> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> <button onClick={this.increment}>+</button> <button onClick={this.decrement}>-</button> <button onClick={this.incrementIfOdd}>increment if odd</button> <button onClick={this.incrementAsync}>increment async</button> </div> </div> ); } } export default connect( state => ({count: state}), {increment, decrement} )(App)7. index.js
import React from 'react'; import ReactDOM from 'react-dom'; import App from "./App"; import {Provider} from 'react-redux'; import store from "./redux/react_redux_counter/store"; ReactDOM.render(<Provider store={store}><App/></Provider> , document.getElementById('root') );8. 效果图
9. 问题:
1)redux默认是不能进行异步处理的;
2)应用中又需要在redux中执行异步任务(ajax,定时器)
下一篇博文,继续优化~~~
