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