如何访问 Redux reducer 内部的状态? [英] How to access state inside Redux reducer?

查看:18
本文介绍了如何访问 Redux reducer 内部的状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个减速器,为了计算新状态,我需要来自动作的数据以及来自不由该减速器管理的状态部分的数据.具体来说,在我将在下面展示的 reducer 中,我需要访问 accountDetails.stateOfResidenceId 字段.

I have a reducer, and in order to calculate the new state I need data from the action and also data from a part of the state not managed by this reducer. Specifically, in the reducer I will show below, I need access to the accountDetails.stateOfResidenceId field.

initialState.js:

export default {
    accountDetails: {
        stateOfResidenceId: '',
        accountType: '',
        accountNumber: '',
        product: ''
    },
    forms: {
        blueprints: [

        ]
    }
};

formsReducer.js:

import * as types from '../constants/actionTypes';
import objectAssign from 'object-assign';
import initialState from './initialState';
import formsHelper from '../utils/FormsHelper';
export default function formsReducer(state = initialState.forms, action) {
  switch (action.type) {
    case types.UPDATE_PRODUCT: {
        //I NEED accountDetails.stateOfResidenceId HERE
        console.log(state);
        const formBlueprints = formsHelper.getFormsByProductId(action.product.id);
        return objectAssign({}, state, {blueprints: formBlueprints});
    }

    default:
      return state;
  }
}

index.js(根减速器):

import { combineReducers } from 'redux';
import accountDetails from './accountDetailsReducer';
import forms from './formsReducer';

const rootReducer = combineReducers({
    accountDetails,
    forms
});

export default rootReducer;

如何访问此字段?

推荐答案

我会使用 thunk为此,这里有一个例子:

I would use thunk for this, here's an example:

export function updateProduct(product) {
  return (dispatch, getState) => {
    const { accountDetails } = getState();

    dispatch({
      type: UPDATE_PRODUCT,
      stateOfResidenceId: accountDetails.stateOfResidenceId,
      product,
    });
  };
}

基本上,您获得了操作所需的所有数据,然后您可以将这些数据发送到您的减速器.

Basically you get all the data you need on the action, then you can send that data to your reducer.

这篇关于如何访问 Redux reducer 内部的状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆