redux 为什么我不能从store中的state返回一个特定的属性,而它在返回其父对象时工作正常?

9avjhtql  于 2023-06-23  发布在  其他
关注(0)|答案(1)|浏览(81)

这可能看起来有点混乱,但基本上我只想在任何组件上使用useSelector钩子从状态本身访问一个属性,以检索一个特定的属性,我的意思是,例如,我配置了我的slice,它具有如下结构的初始状态,但是它应该做得很好,因为我使用useSelector钩子从那里获取这些状态值,但它只在我试图只访问它的父对象但它的属性时才起作用...
在我的组件中,我必须能够访问states.filters.departureTimeRange属性,我很确定它已经有数据,并且在我打印出state.filters本身时已经测试过了。但是我不知道这个状态对象的属性有什么问题,当我试图打印里面的属性时,只返回undefined
总结一下:state.filters还可以,但是state.filters.departureTimeRange或者任何其他属性只会让我得癌症,已经在这个问题上折腾了几个小时了,但是没有运气!任何帮助都是如此感激,提前感谢了很多

我的组件

const DepartureHour = () => {
  const [selectedOption, setSelectedOption] = useState('evening');
  const [departureTime, setDepartureTime] = useState<[number, number]>([0, 24]);
  const dispatch = useDispatch();
  const departureTimeRange = useSelector((state: RootState) => state.filters.departureTimeRange);
 

  useEffect(() => {
    if (departureTimeRange) {
      console.log(departureTimeRange);
    }
  }, [departureTimeRange]);

filtersSlice

interface FiltersState {

    priceRange: [number, number];
    departureTimeRange: [number, number];
    seatLayout: string;
    busCompanies: string[];
    services: string[];
    destination: string[];
    departure: string[];
  }
  
  export interface RootState {
    filters: FiltersState;
  }

  const initialState: RootState = {
    filters: {
      priceRange: [0, 1000],
      departureTimeRange: [0, 24],
      seatLayout: '',
      busCompanies: [],
      services: [],
      destination: [],
      departure: [],
    },
  };

const filtersSlice = createSlice({
    name: 'filters',
    initialState,
    reducers: {
          setDepartureTimeRange(state, action:PayloadAction<FiltersState['departureTimeRange'] >) {
            state.filters.departureTimeRange = action.payload
        },
          //other reducers
})

export const {setDepartureTimeRange} = filtersSlice.actions;

export default filtersSlice.reducer;

rootReducer

const rootReducer = combineReducers({
    seats: seatsReducer,
    selectedSeats: selectedSeatsReducer,
    filters: filtersReducer
});

export default rootReducer;
hgc7kmma

hgc7kmma1#

你好,我想你有双折叠:
将减速器定义为:

filters: filtersReducer

然后定义initialState:

const initialState: RootState = {
    filters: {…}

这基本上给予store.filters.filters
你也有错误的转换为RootState,根状态是store类型,而不是片state类型
所以呢

const departureTimeRange = useSelector((store: RootState) => store.filters.filters.departureTimeRange);

应按预期工作
P.s.:你应该从initialState中删除:RootState,然后你应该从initialState中删除关键字filters,它应该像预期的那样工作(使用当前的useSelector)

相关问题