[英]React-redux Useselector not Working. Cannot read properties of Undefined ('channelId')
I am Creating a React-app and using Reduxjs Toolkit for state management.我正在创建一个 React-app 并使用 Reduxjs Toolkit 进行 state 管理。 I am not able to understand why ChannelID and Channelname are undefined here.
我无法理解为什么 ChannelID 和 Channelname 在这里未定义。 Here is the App.js
这是 App.js
import { useSelector } from 'react-redux'
import { selectChannelId, selectChannelname } from '../../reduxjs toolkit/appSlice'
const Chats = () => {
const user = JSON.parse(localStorage.getItem("user"))
const data = localStorage.getItem("userData");
const [userData, setUserData] = useState(JSON.parse(localStorage.getItem("userData")))
const ChannelId = useSelector(selectChannelId) // Giving Error Here
const channelName = useSelector(selectChannelname) // Giving Error Here
Here is the appSlice这是appSlice
import { createSlice } from "@reduxjs/toolkit";
export const appSlice = createSlice({
"name":'app',
initialState:{
channelId:null,
channelName:null,
},
reducers:{
setChannelInfo: (state,action)=>{
state.channelId = action.payload.channelId
state.channelName = action.payload.channelName
},
}
})
export const {setChannelInfo}= appSlice.actions
export const selectChannelId = (state) => state.app.channelId
export const selectChannelname = (state) => state.app.channelName
export default appSlice.reducer;
Code for Store商店代码
import { createStore } from "redux";
import reducers from "./reducers"
const store = createStore(reducers, {}, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__())
export default store;
Use configureStore to create your store, this is "a friendly abstraction over the standard Redux createStore function that adds good defaults to the store setup for a better development experience."使用 configureStore 创建您的商店,这是“对标准 Redux createStore function 的友好抽象,它为商店设置添加了良好的默认设置,以获得更好的开发体验。” quoted from the rtk doc.
引用自 rtk 文档。
For your case it will be as such对于您的情况,它将是这样的
import appReducer from './%%WhereYourSliceResides
import { configureStore } from '@reduxjs/toolkit'
export const store = configureStore({
reducer: {
app: appReducer,
},
})
Then the selector will pick up state.app from your store.然后选择器将从您的商店中选择 state.app。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.