0

this view doesn't work with redux, i need use redux dispatch inside react class component, but i get error

"Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem."

inspectionView.jsx

import React from "react";
import {
  Text,
  View,

} from "react-native";

import { useSelector, useDispatch } from 'react-redux';
import {
    incrementByAmount,
    selectCount
  } from '../redux/slice.js';


  
  export default class InspectionList extends React.Component {
      constructor(props) {
          super(props);
          
          this.state = {
           
            };
        }
        
        dispatch = useDispatch();
        count = useSelector(selectCount);

 
  render() {
    return (
      
        <View >
            <Text>inspection view</Text>
            <button
          onClick={() => dispatch(incrementByAmount("hello world"))}
          >
          Add Amount
        </button>
            <Text>{{count}}</Text>
        </View>
      
    );
  }
}

Slice.js

import { createSlice } from '@reduxjs/toolkit'

const initialState = {
  value: 0,
}

export const counterSlice = createSlice({
  name: 'counter',
  initialState,
  reducers: {
    incrementByAmount: (state, action) => {
      state.value = action.payload
    },
  },
})

// Action creators are generated for each case reducer function
export const {incrementByAmount } = counterSlice.actions
export const selectCount = (state) => state.counter.value;
export default counterSlice.reducer

store.js

import { configureStore } from '@reduxjs/toolkit'
import counterReducer from './slice'
export const store = configureStore({
  reducer: {
    counter: counterReducer,
  },
})

1 Answers1

1

The error is correct. You can never call any hook inside of a class component, regardless of whether it's a React-Redux hook, a React built-in hook, or any other hook. Only function components can call hooks.

My main advice here would be to write function components instead. There's no good reason to be writing class components today.

See the new React beta docs to learn how to use function components and hooks:

https://beta.reactjs.org

If for some reason you must use class components (and the odds are you don't need to), you can still use the older React-Redux connect API:

markerikson
  • 63,178
  • 10
  • 141
  • 157