我应该如何在redux中构建/传递我的数据或操作

How should I structure/pass my data or actions in redux

本文关键字:我的 数据 操作 构建 redux 我应该      更新时间:2023-09-26

我现在正在像这样转换我的defaultState(我的整个reducer):

import _ from 'lodash';
import { SIGN_UP_STEP, RESET_SIGN_UP } from '../actions/sign-up';
const defaultState = {
  ui: {
    loading: false
  }, metadata: {
    step: 1,
    code: null
  },
  data: {
    name: null,
    email: null,
    password: null,
    number: null,
    access_token: null
  }
}
export default function signUpReducer(state = defaultState, action) {
  switch(action.type) {
  case SIGN_UP_STEP:
    return _.merge({}, state, action.data)
  case RESET_SIGN_UP:
    return defaultState;
  default:
    return state;
  }
}

我现在的行动就像

import request from 'axios';
import _ from 'lodash';
const BACKEND_ROOT = process.env.API_ROOT || 'http://localhost:3000';
export const SIGN_UP_STEP = 'SIGN_UP_STEP';
export const RESET_SIGN_UP = 'RESET_SIGN_UP';
export function signUpStep(data) {
  return {
    type: SIGN_UP_STEP,
    data
  }
}
...

但现在我在思考我应该如何构建或如何做到这一点。如果我应该做从组件到动作或从动作到减速器的格式发送。

比如,我应该这样做吗:

// component
const signUpAction = SignUpActions.signUpStep({
  step: 2,
  name: this.refs.name.value,
  email: this.refs.email.value,
  password: this.refs.password.value
});
dispatch(signUpAction);
// action
export function signUpStep(data) {
  return {
    type: SIGN_UP_STEP,
    {
      metadata: {
        step: data.step
      },
      data: data.data
    }
  }
}

或者先格式化后再发送?

// component
const signUpAction = SignUpActions.signUpStep({
  metadata: {
    step: 2,
  },
  data: {
    name: this.refs.name.value,
    email: this.refs.email.value,
    password: this.refs.password.value
  }
});
dispatch(signUpAction);
// action
export function signUpStep(data) {
  return {
    type: SIGN_UP_STEP,
    data
  }
}

我同意@Kai在评论中的观点,但为了更进一步,我更喜欢显示契约的行为。

export function signUpStep(name, email, password, ...args){
  return { type: SIGN_UP_STEP,
    metadata: {
      step: 2
    },
    data: {name, email, password, ..args}
  }
}
// to call
signUpStep("John", "john@example.com", "Pass1", "doej");
// to access "doej" parameter from function
const githubId = args[0];

显然,这都是个人偏好,但在上面的部分中,您现在在不阅读操作的情况下公开了操作所需的必要字段的明确约定。