首页 > 解决方案 > ts:如何访问redux store里面的state

问题描述

我的减速器集合存储在 rootReducer 中(具有普通减速器和切片减速器)。

我需要使用 useSelector 钩子访问这些减速器中的状态。

我的商店:

const store = configureStore({reducer : rootReducer});

根减速器:

const reducers = {
  getName,
  getSomething,
  getCollection,
  getSomethingelse
}
const rootReducer = combineReducers(reducers);

样本减速器(createSlice):

const initialState:any = {
    nameList:[]
}

const setNameList = createSlice({
    name:"setNameList",
    initialState,
    reducers:{
        setNameList(state,action){
            state.nameList.push(action.payload);
        }
    }
});

另一个 Sample Reducer(正常):

export default function somethingReducer(state = {
    something:{}
}, action) {
    switch(action.type){
        case C.SOMETHING_ZONE:{        
            return {
                ...state
                ,something :action.payload
            }
        }
        default : {}
    }
    return state
}

我试着做,

  const name = useSelector(state => state.getName.nameList)
  const something = useSelector(state => state.getSomething.something)

但出现错误:Property 'getName' does not exist on type 'DefaultRootState'.

标签: reactjstypescriptreduxreact-reduxredux-toolkit

解决方案


你的 RootReducer 有问题。按照以下方式更改 const 变量:

const reducers = {
  getName: setNameList.reducer,
  getSomething: somethingReducer.reducer  
}

不要忘记导入减速器并以相同的方式使用其他减速器。


推荐阅读