让你一次看清晰的redux结合react案例

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;

查看更多,请浏览:http://www.etayun.com/ability/react/95.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值