需要帮助:错误:无效的挂钩调用。钩子只能在函数组件内部调用

时间:2021-06-30 14:36:58

标签: javascript reactjs react-hooks

× 错误:无效的挂钩调用。钩子只能在函数组件的主体内部调用。这可能是由于以下原因之一造成的:

  1. 您的 React 和渲染器版本可能不匹配(例如 React DOM)
  2. 你可能违反了钩子规则
  3. 您可能在同一个应用中拥有多个 React 副本 有关如何调试和解决此问题的提示,请参阅 https://reactjs.org/link/invalid-hook-call
import './App.css';
import {useSelector} from 'react-redux';
import Header from './Header';
import Sidebar from './Sidebar';
import Feed from './Feed';
import { selectUser } from './features/userSlice';
import Login from './Login';

function App() {

  const user = useSelector(selectUser)

  return (
    <div className="app">
      <Header />

      {!user ? (
        <Login />
      ) : (
        <div className="app__body">
          <Sidebar />
          <Feed />
          {/* Widgets */}
        </div>
      )}
    </div>
  );
} 

export default App;

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

export const userSlice = createSlice({
  name: 'user',
  initialState: {
    user: null,
  },
  reducers: {
    login: (state, action) => {
      state.value = action.payload;
    },
    logout: (state) => {
      state.user = null;
    },
  },
});

export const { increment, decrement, incrementByAmount } = userSlice.actions;

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

export default userSlice.reducer;

0 个答案:

没有答案