我有两个初始状态的帖子和一个用户。我能够更新帖子的状态,但不能更新用户的状态。我正在使用JWT将令牌从服务器端发送到客户端。当我在将axios post请求发送到/ 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;