Redux打印脚本导出数组中reducer的状态

u7up0aaq  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(140)

所以我遇到了一个问题,我的reducer是未定义的,我不明白它是什么意思,当它不是数组的时候它是工作的,但是当它是数组的时候它不工作。
我的代码应该是这样的。在我的groupSlice.ts中是这样的

export interface GroupState {
    grouplist: (string)[];
}

const groupInitialState: GroupState = {
    grouplist:['Binary','Jhonny Sins']
}
export const createGroup = createSlice({
    name: 'group',
    initialState:groupInitialState,
    reducers:{  
        addGroup: (state,action) => {
            state.grouplist.push(action.payload)
        },
        subGroup: ( state,action ) => {
            state.grouplist.filter((group) => group != action.payload)
        }
    }
})
...

然后我把它存储在我的store.ts

import { configureStore, ThunkAction, Action } from '@reduxjs/toolkit';
import { createGroup }  from '../features/counter/groupSlice';

export const store = configureStore({
  reducer: {
    groupings: createGroup.reducer,
  },
});

export type AppDispatch = typeof store.dispatch;
export type RootState = ReturnType<typeof store.getState>;
export type AppThunk<ReturnType = void> = ThunkAction<
  ReturnType,
  RootState,
  unknown,
  Action<string>
>;

然后把hook.ts传给我的state在减速器里。

import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux';
import type { RootState, AppDispatch } from './store';

export const useAppDispatch = () => useDispatch<AppDispatch>();
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;

但是当我在Group.tsx中传递它时,它说grouplist未定义,即使我已经输入了an array at string[]

import React,{ useState,useEffect } from 'react'

import styles from './Group.module.css'

import {
    addGroup,
    subGroup
} from './groupSlice';
import { useAppSelector, useAppDispatch } from '../../app/hooks';
import { RootState } from '../../app/store';

// HERE IS MY ERROR THAT DOESN"T WORK>
export const selectCount = (state: RootState) =>  {
    console.log(state.groupings?.grouplist)
    const groupList = state.groupings?.grouplist
    return groupList;
}

const Grouping = () => {

    const groups = useAppSelector(selectCount);
    const dispatch = useAppDispatch();
    const [groupName, setGroupName] = useState('');

    return (
        ...
    )
}

export default Grouping

所以我想说我的grouplist是未定义的,但我不知道为什么,因为我已经在那里输入了一个列表值。有人能发现这里的错误吗?谢谢。

holgip5t

holgip5t1#

subGroup减速器中:

state.grouplist.filter(...)

这只会返回过滤后的数组,而不会对其进行更改(与push不同),因此需要对其进行重新赋值:

state.grouplist = state.grouplist.filter(...)

相关问题