所以我遇到了一个问题,我的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
是未定义的,但我不知道为什么,因为我已经在那里输入了一个列表值。有人能发现这里的错误吗?谢谢。
1条答案
按热度按时间holgip5t1#
在
subGroup
减速器中:这只会返回过滤后的数组,而不会对其进行更改(与
push
不同),因此需要对其进行重新赋值: