【发布时间】: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]);
如果我记录我的状态,这就是我得到的:
另外,我使用处理 onClick 事件的状态函数:
onClick={() => { dispatch(changePathName(['/home'])) }}
我在启动应用程序时遇到的错误:“TypeError: Cannot read properties of undefined (reading 'pathnames')”
【问题讨论】:
标签: javascript reactjs redux redux-toolkit