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

本文介绍Redux-Actions的安装及使用,通过简化reducer和action的联系,提高代码的可读性和维护性。文章详细讲解了如何创建action,组件中引入使用,以及在reducer中应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、安装

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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值