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

一、安装

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)

猜你喜欢

转载自www.cnblogs.com/nanianqiming/p/11225428.html