【问题标题】:redux toolkit slice accessing variable problemredux 工具包切片访问变量问题
【发布时间】:2021-09-08 01:20:07
【问题描述】:

我在我的代码中实现了切片方法,但遇到了问题。当我尝试使用操作、reducers、存储和类型访问老式方式时,它可以工作。这是我的新店:

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'])) }}

我在启动应用程序时遇到的错误:“TypeError: Cannot read properties of undefined (reading 'pathnames')”

【问题讨论】:

    标签: javascript reactjs redux redux-toolkit


    【解决方案1】:

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

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

    【讨论】:

    • 我试过了,但是没有用。最后,我不明白的是在 ``` configurestore() ``` 函数中创建新对象。所以 ``` const pathnames = useSelector(state => state.navPannel[0].pathnames[0]);``` 正常工作。
    猜你喜欢
    • 2022-12-31
    • 1970-01-01
    • 2020-07-30
    • 2020-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-24
    • 2023-01-31
    相关资源
    最近更新 更多