我有一个组件,可在浏览器中显示电子邮件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: " "
};