React@16.x(53)Redux@4.x(2)- action

发布于:2024-07-11 ⋅ 阅读:(62) ⋅ 点赞:(0)

1,特点

是一个平面对象(plain-object)。换句话说,就是通过字面量创建的对象,它的 __proto__ 指向 Object.prototype

该对象有2个属性:

const action = {
	type: 'add',
	payload: 3
}

1.1,payload

表示额外需要传递的附加数据。

只是约定俗成用该属性,不做强制要求。

1.2,type

1,必须type 属性,用于描述操作的类型,但没有对 type 值的类型做限制。

2,在大型项目中,由于操作类型比较多,为了避免硬编码,会将 actiontype 放到一个单独的文件中。

3,为了方便传递 action,通常会使用一个纯函数来创建它。该函数被称为 action creator

纯函数:

  • 不能改变参数。
  • 没有异步。
  • 不对外部环境中的数据有影响。

举例:

// actionTypes.js
export const ADD = Symbol("add");
export const SET = Symbol("set");
// action.js
import { ADD, SET } from "./actionTypes";

export function getAddAction() {
    return {
        type: ADD,
    };
}

export function getSetAction(newValue) {
    return {
        type: SET,
        payload: newValue,
    };
}
import { createStore } from "redux";
import { ADD, SET } from "./actionTypes";
import * as numberAction from "./action";

function reducer(state, action) {
    if (action.type === ADD) {
        return state + 1;
    } else if (action.type === SET) {
        return action.payload;
    }
    return state;
}

const store = createStore(reducer, 10);
store.dispatch(numberAction.getAddAction());
console.log(store.getState()); // 11
store.dispatch(numberAction.getSetAction(3));
console.log(store.getState()); // 3

1.3,bindActionCreators

为了更方便的利用 action creator 来分发 actionredux 提供了 bindActionCreators

它可以创建 action 后自动完成分发。

  • 第1个参数,action creator 的集合。
  • 返回值,一个新的对象,和第1个参数的属性名一致。
import { createStore, bindActionCreators } from "redux";
import * as numberAction from "./action";

// ...

const store = createStore(reducer, 10);
const bindActions = bindActionCreators(numberAction, store.dispatch);

// store.dispatch(numberAction.getAddAction());
bindActions.getAddAction();
// store.dispatch(numberAction.getSetAction(3));
bindActions.getSetAction(3);

下篇文章 Redux-reducer介绍

以上。