redux toolkit slice 访问变量问题

redux toolkit slice accessing variable problem

我在我的代码中实现了切片方法,但遇到了问题。当我尝试使用 actions、reducer、store 和 types 访问老式方法时,它起作用了。这是我的新店:

import navPannelReducer from './navpannelSlice';



export const store = configureStore({
    reducer: {
        navPannel: navPannelReducer
    }
})

这是 Slice 元素:


export const navPannelSlice = createSlice({
    name: "navPannel",
    initialState: [{
        pathnames: [document.location.pathname]
    }],
    reducers: {
        changePathName: (state, action) => {
            return { ...state, pathnames: action.payload }
        },
    },
});

export const {
    changePathName
} = navPannelSlice.actions;

export default navPannelSlice.reducer;

这里我尝试获取变量:

const dispatch = useDispatch();
const pathnames =  useSelector(state => state.pathnames.pathnames[0]);

如果我记录我的状态,这是我得到的:

CLICK

CLICKAGAIN

此外,我使用了处理 onClick 事件的状态中的函数:

onClick={() => { dispatch(changePathName(['/home'])) }}

我在启动我的应用程序时遇到的错误:“类型错误:无法读取未定义的属性(读取 'pathnames')”

因为你在reducer中使用了navPannel。所以像这样更新:

const pathnames =  useSelector(state => state.navPannel.pathnames[0]);