【发布时间】:2020-01-20 10:00:44
【问题描述】:
我有一个组件可以在浏览器中显示电子邮件 cookie 的值,但如果您在 URL 中传递新电子邮件,它应该会更新。
目前,如果我在 URL 中传递一封新电子邮件,我可以看到 cookie 已更新,但新电子邮件未呈现在页面上,仅显示前一个。
import React from "react";
import Helper from "plugins/helper";
class emailField extends React.Component {
constructor(props) {
super(props);
this.state = {
cookie: ""
};
this.handleChange = this.handleChange.bind(this);
this.updateCookie = this.updateCookie.bind(this);
}
shouldComponentUpdate(nextProps, nextState) {
if (nextState.cookie !== this.state.cookie) {
this.updateCookie();
return true;
}
return false;
}
componentDidMount() {
this.updateCookie();
}
updateCookie() {
const cookie = Helper.getCookie("email");
const query = window.location.href;
const emailUrl = query.match(/email=/g);
if (cookie && emailUrl) this.setState({ cookie });
}
handleChange(e) {
Helper.setCookie("email", e.target.value);
}
render() {
const { cookie } = this.state;
const { id } = this.props;
return (
<div id={id}>
<div className="row noEmailUrl" style={{ display: "none" }}>
<div className="col-md-2"></div>
<div className="col-md-10">
<input
className="email form-control emailPrimary"
placeholder="Please enter your email address"
name="EMAIL_ADDRESS_"
value={cookie}
onChange={this.handleChange}
/>
</div>
</div>
<div className="row emailUrl">
<div className="col-md-8 emailAddress">
<span className="email">{cookie}</span>
</div>
<div className="col-md-4 editBtn">
<button type="button" className="changeAddress">
Edit email
</button>
</div>
</div>
</div>
);
}
}
export default emailField;
emailField.defaultProps = {
id: " "
};
【问题讨论】: