【问题标题】:State undefined when using combineReducers()使用 combineReducers() 时的状态未定义
【发布时间】:2020-06-12 19:48:06
【问题描述】:

当我想组合我的 2 个减速器时,我无法获得我的状态。

当我只使用一个减速器时一切正常,但当我尝试使用 combineReducers() 时,我无法再获得我的状态。

 const initialState = 
{ 
    films: []
}

const filmsReducer = (state = initialState, action) => {
    let nextState;

    switch (action.type)
    {
        [...]
        default:
            return state;
    }
}

export default filmsReducer;
const initialState = { checkedCategories: [''] }

const categoriesReducer = (state = initialState, action) => {
    let nextState;

    switch (action.type) {
        [...]
        default :
            return state;
    }
}

export default categoriesReducer;
import { combineReducers } from 'redux';

import films from './films-reducer';
import categories from './categories-reducer';

export default combineReducers({films, categories});
import { createStore } from 'redux';

import rootReducer from '../reducers/index';

export default createStore(rootReducer);

下面是我得到一个未定义的地方

import React, { useEffect, useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';

export const Categories = (props) => {
    const [categories, setCategories] = useState([]);
    const checkedCategories = useSelector(state => state.checkedCategories)
    const dispatch = useDispatch();

    const categoryToggle = (category) => {
        console.log(checkedCategories);
        if (checkedCategories.findIndex(item => item.id === category.id) !== -1)
            return (<div>caca</div>)
    }
[...]
}

我得到了初始状态和两者的默认返回值。

【问题讨论】:

  • 你能说明你在哪里使用它们吗?它在哪里未定义?
  • @BrianThompson 刚刚做了

标签: reactjs redux react-redux


【解决方案1】:

通过添加combineReducers,您改变了状态对象的结构。

该结构以前是包含checkedCategories 的单个对象。像这样的:

state: {
  checkedCategories: ['']
}

但现在是这样的:

state: {
  films: {
    films: []
  }, 
  categories: {
    checkedCategories: ['']
  }
}

您需要相应地调整您的选择器:

const checkedCategories = useSelector(state => state.categories.checkedCategories)
//                                                   ^ nested one level deeper now

【讨论】:

  • 谢谢,但是如何更深入地了解关卡的名称?
  • 您通过将对象传递给combineReducers来自己命名它:combineReducers({films, categories});
【解决方案2】:

您可能想尝试将导出的组合减速器命名为 rootReducer -

export const rootReducer = combineReducers({films, categories});

或者如果你喜欢冗长

const rootReducer = combineReducers({films, categories});

export rootReducer;

祝你好运,黑客愉快。

【讨论】:

  • 可以使用任何名称导入默认导出。
  • 将其从默认更改为命名将在此处无效
  • 啊谢谢布赖恩。这只是在黑暗中拍摄的。我在想,如果从不导出 rootReducer 的文件中导入 rootReducer 可能会产生影响,但很高兴知道。状态对象肯定会发生变化。我喜欢你的回答。
猜你喜欢
  • 1970-01-01
  • 2019-07-10
  • 2022-07-13
  • 1970-01-01
  • 2019-12-03
  • 2020-12-20
  • 1970-01-01
  • 2021-01-18
  • 2021-11-03
相关资源
最近更新 更多