我的导航栏上有一个名为Login的导航链接(我使用了引导导航栏(。成功登录后,我想使用react redux(而不是redux工具包(将login替换为用户名。请帮我写减速器和动作码。由于我是redux的初学者,我不知道如何在reducer和操作文件中进行编码,这对我来说非常困惑
Navbar组件(Navbar.js(
import React from 'react';
import { Link } from 'react-router-dom';
import { useSelector } from 'react-redux';
const Navbar = () => {
const {username} = useSelector((state) => state.user);
return (
<div>
<nav className="navbar navbar-expand-lg">
<div className="container-fluid">
<Link className="navbar-brand" to="/hommepage">Ebuy</Link>
<button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria- expanded="false" aria-label="Toggle navigation">
<span className="navbar-toggler-icon">
<i className="fas fa-bars" style={{color: 'white', fontSize: '28px'}}></i>
</span>
</button>
<div className="collapse navbar-collapse" id="navbarSupportedContent">
<ul className="navbar-nav me-auto mb-2 mb-lg-0">
<li className="nav-item">
<Link className="nav-link" aria-current="page" to="/homepage">Home</Link>
</li>
<li className="nav-item dropdown">
<Link className="nav-link dropdown-toggle" to="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
Select Category
</Link>
<ul className="dropdown-menu" aria-labelledby="navbarDropdown">
<li><Link className="dropdown-item" to="/skincare">Skincare Products</Link></li>
<li><Link className="dropdown-item" to="/stationary">Stationary Products</Link></li>
<li><Link className="dropdown-item" to="#">Clothing</Link></li>
</ul>
</li>
</ul>
<div className="d-flex">
<ul className="navbar-nav me-auto mb-2 mb-lg-0">
<li className='nav-item'>
<Link className="nav-link" to="/">Login</Link>
</li>
</ul>
</div>
</div>
</div>
</nav>
</div>
);
};
export default Navbar;
减速器
const initialState = {
username: null,
}
export const userReducer(state = initialState, action) {
switch (action.type) {
case "CHANGE_USERNAME":
return {
...state,
username: action.payload,
}
default:
return state
}
}
动作
export const changeUserName = (name) => {
return {
type: "CHANGE_USERNAME",
payload: name
}
}
登录后调用此
const dispatch = useDispatch()
const login = () => {
... login logic here
dispatch(changeUserName("user-1"))
}
在导航栏
const { username } = useSelector(state=> state.user)
在Navbar组件中,您应该从redux中获取用户名,请尝试以下操作:
const {username} = useSelector(state=> state.yourReducerName)
在此之后,在您的jsx中:您应该编写这样的条件:
{username ? (<div>{username}</div>): ()<span>Login</span>}
编辑:
请参考这个沙箱示例,并查看reducer和操作文件,以及导航栏组件。如果帖子对您有帮助,请告诉我们:(