【问题标题】:state variables are coupled with reducer names in redux状态变量与 redux 中的 reducer 名称耦合
【发布时间】:2019-07-05 02:37:08
【问题描述】:

这可能是一个非常愚蠢的问题,但我在它周围徘徊了一段时间。我有一个 React 项目(使用 Redux)。在mapStateToProps 中,如果我尝试以

的身份直接访问状态,则状态值将以 undefined 的形式出现
const mapStateToProps = state => ({ data: state.data });

相反,我总是必须指定我的减速器名称(在其中处理此特定状态的减速器)才能访问状态值:

const mapStateToProps = state => ({ data: state.customReducer.data });

这是我的代码:

import { combinedReducer } from 'redux;
import customReducer from './customReducer'; 

const rootReducer = combineReducer({
      customReducer
});

export default rootReducer;

customReducer.js : 如下

  const initialState = {};

    const customReducer = ( state = initialState, action ) => {
         const { type, payload } = action;

         switch (type) {
               case 'SOME_ACTION':
                    return {
                         ...state,
                         data: payload.data
                    }
                    break;

               default:
                     return state;
         }
    } 

export default customReducer;

store.js

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from '../reducers';

const configStore = () => {
     return createStore (
           rootReducer,
           applyMiddleware(thunk)
     );
} 

const store = configStore();

export default store;

有谁知道实施中出了什么问题?或者它是从不同商店访问不同状态值的方式?

我怎样才能直接访问任何状态变量

data: state.`state_value` , instead of ,  data : state.`reducerName`.`state_value` ?

对此的任何帮助将不胜感激。

【问题讨论】:

    标签: reactjs redux react-redux state


    【解决方案1】:

    您的实现没有任何问题,这正是combineReducers 的工作方式。 reducer 名称用于对存储进行分区(例如,users reducer 中的所有内容都将在 state.users 下)。

    如果您不想在mapStateToProps 中使用reducer 的名称,可以使用selectors。但是,在选择器中,您仍然必须使用 state.reducerName

    如果您真的不想通过多个层来获得您想要的值,您可以为每个值创建一个单独的减速器(即在您的示例中,减速器将被命名为data )。不过,这显然不是首选方式。

    【讨论】:

      【解决方案2】:

      好吧,combineReducers 并没有真正使用 reducer 名称,而是您为其指定的属性名称。如果你这样做:

      const rootReducer = combineReducer({
        foo: customReducer,
      });
      

      您将能够通过state.foo.data 访问数据。

      【讨论】:

        猜你喜欢
        • 2023-03-23
        • 1970-01-01
        • 2018-11-14
        • 2023-03-14
        • 1970-01-01
        • 2017-08-28
        • 1970-01-01
        • 1970-01-01
        • 2019-07-28
        相关资源
        最近更新 更多