node.js - 无法使用 usereducer 函数设置状态
问题描述
我有两个初始状态帖子和用户。我可以更新帖子的状态,但不能更新用户的状态。我正在使用 JWT 将令牌从服务器端发送到客户端。当我将 axios 发布请求发送到 /login 后收到的响应控制台输出时,我能够获取从服务器发送的令牌。但是,当我使用 reducer 函数将用户状态设置为 action.payload 并将其发送到 Login.js 时,我将用户值设置为 []。
const initialValue = {
posts: [],
users: []
}
const reducer = (state, action) => {
switch (action.type) {
case 'LOGIN':
return {
...state,
users: [action.payload]
}
default:
return state
}
}
export const Globalcontext = createContext(initialValue)
function App() {
const [state, dispatch] = useReducer(reducer, initialValue)
function login(User) {
axios.post(`http://localhost:4000/blog/login`, User).then(res => {
dispatch({
type: 'LOGIN',
payload: res.data
})
console.log(res.data) /* I am getting the desired token value */
}).catch(err => {
console.log(err)
})
}
收到用户状态后,我尝试将 localStorage 项目值设置为该状态,以便我可以对用户进行身份验证。
const Login = () => {
let history = useHistory();
const [email, setemail] = useState('');
const [password, setpassword] = useState('');
const { login, users } = useContext(Globalcontext);
const handleSubmit = (e) => {
e.preventDefault();
const addedValue = {
email,
password,
};
localStorage.setItem('usertoken', users);
console.log(localStorage.getItem('usertoken')); /* Here, I am getting [] as the output. */
login(addedValue);
setemail('');
setpassword('');
history.push('/blog');
};
return (
<div>
<form onSubmit={handleSubmit}>
<input
type='email'
name='email'
value={email}
placeholder='E-mail address'
onChange={(e) => setemail(e.target.value)}
/>
<input
type='password'
name='password'
value={password}
placeholder='Password'
onChange={(e) => setpassword(e.target.value)}
/>
<button
className='btn btn-secondary'
style={{ backgroundColor: '#007bff', margin: '5px' }}
type='submit'
value='submit'
>
Login
</button>
</form>
</div>
);
};
export default Login;
解决方案
推荐阅读
- php - PHP - 根据项目名称的 SUM 编号
- python - 无法在 Spyder (Python 3.6) 中读取 .CSV 文件,这不是路径或字符问题
- java - 用于下载文件的 Spring 端点成功 (200),但调用 /error 端点 (406)
- bootstrap-4 - 如何使用 Bootstrap 4 显示各种屏幕
- vb.net - 通过函数将小数添加到文本框
- java - TextView 阻止底部导航
- python - 编写一个函数,通过删除指定列的四分位数区域内的行来子集数据帧
- python - 如何使用以前的版本制作 python 文件?
- swift - 从字符串中提取项目
- c# - 在 C# 中运行 SQL 查询后,很少有列检索为“null”