简体   繁体   中英

React-redux Useselector not Working. Cannot read properties of Undefined ('channelId')

I am Creating a React-app and using Reduxjs Toolkit for state management. I am not able to understand why ChannelID and Channelname are undefined here. Here is the 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

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;

Error Message在此处输入图像描述

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." quoted from the rtk doc.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM