简体   繁体   中英

How to use 'useDispatch' and 'useSelector' in class based component

I have one class where I'm using useDispatch and setting my data in reducer and I want to use my data in another class, like how I'm using useDispatch in functional component and using useSelector , I can fetch the the data from anywhere inside project, like that I want in class based component.

import { createSlice } from "@reduxjs/toolkit";

export const userSlice = createSlice({

  name: "user", initialState: {

    user: null,

  },

  reducers: {

    setUser: (state, action) => {

      state.user = action.payload.user;

    },

    logout: (state) => {

      state.user = null;

    },

  },

});

export const { setUser, logout } = userSlice.actions;

export const selectUser = (state) => state.user;

export default userSlice.reducer;

// functional component One ..........................
const dispatch = useDispatch();
dispatch(setUser({ user: "om" }));

// functional component two  ..........................
const selectcter =  useSelector(selectUser);
console.log(selectcter);

` like that I want to use in class based component any help?

You can't mix React hooks inside class component. Either you change the class component into functional component with hooks, or use the Redux logic that fit to class components.

actually, useSelect and useDispatch is nothing but just a replacement of mapStateToProps and mapDispatchToProps which we pass in connect hoc when we try to connect our component with the redux store.

When you are working with the class component you can't use the useDispatch and useSelector because these are hooks that react-redux provides for use in the functional components for the same behavior which connect provides in the class component. So for your case have a look at how to use connect from react-redux and how to pass mapDispatchToProps and mapStateToProps if you are using the class component. here is documentation for connect

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