【发布时间】:2020-11-11 05:23:24
【问题描述】:
当我尝试使用下面创建的方法登录时,登录组件出现问题。
下面是代码示例:
export default function Signin(props) {
const classes = useStyles();
const [values, setValues] = useState({
email: '',
password: '',
error: '',
redirectToReferrer: false,
});
const handleSubmit = () => {
const user = {
email: values.email || undefined,
password: values.password || undefined,
};
signin(user).then((data) => {
if (data.error) {
setValues({ ...values, error: data.error });
} else {
auth.authenticate(data, () => {
setValues({ ...values, error: '', redirectToReferrer: true });
});
}
});
};
const handleChange = (name) => (event) => {
setValues({ ...values, [name]: event.target.value });
};
const { from } = props.location.state || {
from: {
pathname: '/',
},
};
const { redirectToReferrer } = values;
if (redirectToReferrer) {
return <Redirect to={from} />;
}
}
如果我保存此代码,则会出现错误:
无法读取未定义的属性状态。
当我注释掉这个 {from} 时,会出现登录表单。但是当我点击提交按钮时出现另一个错误:
无法读取未定义的属性错误。
这是我的登录方法:
const signin = async (user) => {
try {
let response = await fetch('http://localhost:4000/auth/signin', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
credentials: 'include',
body: JSON.stringify(user),
});
return await response.json();
} catch (err) {
console.log(err);
}
};
和认证方法:
const auth = {
authenticate(jwt, cb) {
if (typeof window !== 'undefined')
sessionStorage.setItem('jwt', JSON.stringify(jwt));
cb();
},
};
export default auth;
【问题讨论】:
-
can not read property state of undefined,解决这个问题props.location && props.location.state || ... -
@Naren 解决了。非常感谢兄弟
-
很高兴,成功了!!
标签: reactjs authentication fetch jwt-auth