下面的代码部分
console.log(hub)
console.log(hub2)
在控制台中未定义。 我不知道为什么...
当用户登录时 我可以得到以下Json数据。
{
"hubs": [
"111.com",
"222.com"
}
当我使用“setHub功能”时, 我想将 URL“222.com”分配给 hub 变量 但它是“未定义的”。 奇怪的是
console.log(response.data.hubs[1])
在控制台显示为222.com
这是完整的代码
const Login = () => {
const [hub, setHub] = useState();
const [hub2, setHub2] = useState();
console.log(hub)
console.log(hub2)
const getJwt = async (data) =>{
const email_encoded = btoa(data.email)
const password_encoded = btoa(data.password)
axios.defaults.headers.get['Access-Control-Allow-Origin'] = '*';
await axios.get('xxx.com', {
auth: {
username: data.email,
password: data.password,
}
})
.then(function (response) {
console.log("logged in!");
setCookie('accesstoken', response.data.token, { path: '/' }, { httpOnly: true });
setCookie('refreshtoken', response.data.refresh_token, { path: '/' }, { httpOnly: true });
console.log(response.data.hubs[0])
console.log(response.data.hubs[1])
setHub(response.data.hubs[1]);
setHub2(response);
})
.catch(err => {
console.log("miss");
alert("Email or Password is wrong!");
});
};
return (
<>
<form onSubmit={handleSubmit(getJwt)}>
<input placeholder='Email Address' className='form-control login_form' {...register('email')} />
<div className="login_password_section">
<input placeholder='Password' className='form-control login_form' />
<span
onClick={togglePassword}
role="presentation"
className="password_reveal"
>
</span>
</div>
</form>
</>
);
}
export default Login;
在控制台中未定义。不知道为什么
它们是未定义的,因为您在初始化后就记录了它们。其中未定义为默认值。