重新过一遍该项目,发现概念完全没有分清,我查找了很多文章资料,最后重写,效果如下。
hDH易塔云建站-模板下载,web开发资源,技术博客
hDH易塔云建站-模板下载,web开发资源,技术博客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.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.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;
预览结果:
hDH易塔云建站-模板下载,web开发资源,技术博客![](/d/file/p/9149b4ca59ed6a452712e5eede4e9a84.png)