查看: 26|回复: 0

【react】---redux-actions的基本使用---【巷子】

[复制链接]

3

主题

0

回帖

0

积分

热心网友

金币
0
阅读权限
220
精华
0
威望
0
贡献
0
在线时间
0 小时
注册时间
2008-11-19
发表于 2019-7-22 13:56:00 | 显示全部楼层 |阅读模式

 

一、安装

cnpm install --save redux-actions

 

二、为什么使用 redux-actions

reducer使用switch case语句进行action类型判断,当action很多时候,reducer内容就不那么直观了。redux-actions简化了reducer和action的联系

 

三、基本使用

1、创建action/actionCreator.js

import { createAction } from 'redux-actions';
export const addnum = createAction('ADDNUM')

2、组件中引入使用

import React,{Component} from "react";
import store from "./store"
import {addnum} from "./action/actionCreator"
export default class App extends Component{
  constructor(){
    super()
    this.state = store.getState();
    store.subscribe(this.handleUpdate.bind(this))
  }
  render(){
    let {n} = this.state;
    return (
      <div>
        <h2>{n}</h2>
        <button onClick={this.handleClick.bind(this)}>点击</button>
      </div>
    )
  }
  handleClick(){
    store.dispatch(addnum());
  }
  handleUpdate(){
    this.setState(store.getState())
  }
}

3、reducer中使用

import {handleActions} from 'redux-actions';
const defaultState = {
    n:10
}

export default handleActions({
    ADDNUM: (state, action) => {
        let newState = {...state};
        newState.n++;
        return newState;
    },
}, defaultState)

 



来源:https://www.cnblogs.com/nanianqiming/p/11225428.html
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

相关侵权、举报、投诉及建议等,请发 E-mail:qiongdian@foxmail.com

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.

在本版发帖返回顶部