redux的使用步骤
一、安装redux和thunk中间件。
npm install redux --save
npm install thunk --save
二、redux的使用过程。
①:使用creatStore创建一个唯一store。
Store.js
import {createStore, applyMiddleware, compose} from 'redux'
import thunk from 'redux-thunk'
import {Reducer} from './Reducer'
// 创建一个store,store就是纯数据状态,
// 是数据存储器,只关心数据状态。
// 数据是要初始值的,本例中初始值只有一个数字。
// 而createStore(一参:是一个reducer;二参:是状态的初始值;三参:store enhancer,数据增强,没用过)
const initValues = 10;
const Store = createStore(Reducer, initValues, compose(applyMiddleware(thunk)));
export default Store;
②:创建Reducer。它要改变的组件,它获取state和action。
Reducer.js
import React from 'react'
//定义actionType类型
const makemoney = '挣钱';
const spendmoney = '花钱';
export function Reducer (state, action) {
switch (action.type) {
case makemoney:
return state + 1;
case spendmoney:
return state - 1;
default:
return 10;
}
}
//定义actions动作
export function MakeMoney () {
return {type: makemoney}
}
export function SpendMoney () {
return {type: spendmoney}
}
③:创建View视图部分:
1,生成新的state 用subscribe监听每次修改情况
2,dispatch 一个派发方法,将action 派发给reducer 更改state
View.js
import React from 'react'
import Store from './Store'
import { MakeMoney, SpendMoney } from './Reducer'
class View extends React.Component{
constructor (props) {
super(props);
this.handleItemDecrement = this.handleItemDecrement.bind(this);
this.handleItemIncrement = this.handleItemIncrement.bind(this);
this.state = {
value: Store.getState(),
};
Store.subscribe(
() => {
this.setState({value: Store.getState()})
}
)
}
handleItemDecrement(spendmoney){
const actionType = {type: spendmoney}
Store.dispatch(MakeMoney(actionType))
}
handleItemIncrement(makemoney){
const actionType = {type: makemoney}
Store.dispatch(SpendMoney(actionType))
}
render () {
const money = this.state.value;
// console.log(money);
return(
<div>
<h1>我现在有{money}块钱</h1>
<button onClick={this.handleItemDecrement}>挣钱</button>
<button onClick={this.handleItemIncrement}>花钱</button>
</div>
)
}
}
export default View;