您好,我正在尝试从 redux 的 loginSlice 中的状态中提取电子邮件以显示电子邮件,但我不知道为什么不起作用,我正在使用 redux 开发工具,我可以看到所有元素已填充,但一旦我点击登录,电子邮件就不会在我的导航栏中显示 这是我的登录切片
import axios from 'axios';
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
export const loginUser = createAsyncThunk(
'login/loginUser',
async (args, { getState }) => {
const {
login: {
user: { email, password },
},
} = getState();
return axios
.post(
'http://localhost:3001/sessions',
{
user: {
email,
password,
},
},
{ withCredentials: true },
)
.then((response) => {
if (response.data.status === 'created') {
return response.data;
}
});
},
);
const initialState = {
user: {
email: '',
password: '',
},
loading: false,
error: null,
};
const loginSlice = createSlice({
name: 'login',
initialState,
reducers: {
setUserProperty: (state, action) => {
const { name, value } = action.payload;
state.user[name] = value;
},
logout: (state) => {
state.user = null;
},
},
extraReducers: (builder) => {
builder
.addCase(loginUser.pending, (state, action) => {
state.loading = true;
})
.addCase(loginUser.fulfilled, (state, action) => {
state.user = action.payload;
// state.user.email = action.payload.user.email;
// state.user.password = action.payload.user.password;
state.loading = false;
})
.addCase(loginUser.rejected, (state, action) => {
state.error = action.error.message;
state.loading = false;
});
},
});
export const { setUserProperty, logout } = loginSlice.actions;
export default loginSlice.reducer;
export const selectIsLoginLoading = (state) => state.login.loading;
export const userEmail = (state) => state.login.user.email;
这是我的导航栏组件,我正在尝试调用电子邮件
import React from 'react';
import { Navbar, Nav } from 'react-bootstrap';
import { Link } from 'react-router-dom';
import { useDispatch, useSelector } from 'react-redux';
import { logout, userEmail } from '../features/user/loginSlice';
const NavigationBar = (props) => {
const dispatch = useDispatch();
const email = useSelector(userEmail);
console.log(email);
const handleLogout = (e) => {
dispatch(logout());
e.preventDefault();
};
return (
<div>
<Navbar bg="primary" variant="dark">
<Navbar.Brand href="#home">Expenses Tracker</Navbar.Brand>
<Nav className="mr-auto">
<Link to="/" className="text-light">
Home
</Link>
<Link to="/register" className="text-white mx-2">
Register
</Link>
<Link to="/login" className="text-light">
Login
</Link>
<li>
<a
href="?"
className="text-light mx-2"
onClick={(e) => handleLogout(e)}
>
{' '}
Logout
</a>
</li>
</Nav>
<Navbar.Toggle />
<Navbar.Collapse className="justify-content-end">
{/* <Navbar.Text>Hello: {props.useremail}</Navbar.Text> */}
<Navbar.Text>Hello: {email}</Navbar.Text>
</Navbar.Collapse>
</Navbar>
</div>
);
};
export default NavigationBar;
问题在于导航栏中没有呈现。我做错了什么?