上代码:
export const setCookie = (name, value, expiryDate) => {
let currentDate = new Date();
currentDate.setDate(currentDate.getDate() + expiryDate);
document.cookie = name + '=' + value + '; expires=' + currentDate;
};
export const getCookie = name => {
let arr = document.cookie.split('; ');
for (let i = 0; i < arr.length; i++) {
let arr2 = arr[i].split('=');
if (arr2[0] === name) {
return arr2[1];
}
}
return '';
};
export const removeCookie = name => {
setCookie(name, 1, -1);
};
<Checkbox
checked={this.state.rememberPassword}
onChange={this.onChange}
>
记住密码
</Checkbox>
onChange = e => {
const { username, password } = this.props.form.getFieldsValue();
this.setState(
{
rememberPassword: e.target.checked,
},
() => {
if (e.target.checked) {
setCookie('username', username, 1);
setCookie('password', password, 1);
} else {
removeCookie('username');
removeCookie('password');
}
}
);
};
组件初始化:
checkRememberPassword = () => {
if (getCookie('username') !== '' && getCookie('password') !== '') {
this.props.form.setFieldsValue({
username: getCookie('username'),
password: getCookie('password'),
});
this.setState({
rememberPassword: true,
});
}
};
小结:记住密码功能其实就是对cookie的操作,把账号和密码存储到cookie里面,设置一个过期时间,在过期时间之前都可以拿到存储的数据。