我正在使用 Redux 创建一个 React 应用程序,在我的帐户设置页面上,我有一个表单,我希望预先填充用户的信息,然后让他们能够编辑字段并更新他们的个人资料。我的代码如下:
class UpdateProfile extends Component {
constructor(props) {
super(props);
this.props.getCurrentProfile();
this.state = {
firstName: "",
lastName: "",
email: "",
gender: "",
bday: "",
address1: "",
address2: "",
zipCode: "",
phone: "",
contactMethod: "",
plan: "",
apptReminders: true,
updates: true,
errors: {}
};
// Bind functions
this.onChange = this.onChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);
}
// static getDerivedStateFromProps(nextProps) {
// if (nextProps.profile) {
// let personal = nextProps.profile.profile.personalInfo;
// let account = nextProps.profile.profile.accountInfo;
// return {
// firstName: personal.firstName,
// lastName: personal.lastName,
// email: personal.email,
// address1: personal.address1,
// address2: personal.address2,
// zipCode: personal.zipCode,
// phone: personal.phone,
// contactMethod: account.contactMethod,
// plan: account.plan,
// apptReminders: account.alerts.apptReminders,
// updates: account.alerts.updates
// };
// } else {
// return null;
// }
// }
componentWillReceiveProps(nextProps) {
if (nextProps) {
let personal = nextProps.profile.profile.personalInfo;
let account = nextProps.profile.profile.accountInfo;
this.setState({
firstName: personal.firstName,
lastName: personal.lastName,
email: personal.email,
address1: personal.address1,
address2: personal.address2,
zipCode: personal.zipCode,
phone: personal.phone,
contactMethod: account.contactMethod,
plan: account.plan,
apptReminders: account.alerts.apptReminders,
updates: account.alerts.updates
});
}
}
this.props.getCurrentProfile() 向 mongoDB 发送 axios 请求,接收当前用户的 profile。
问题是如果我使用 getDerivedStateFromProps 方法,文本字段是静态的,无法编辑。即使使用 componentWillMount 方法,如果我从浏览器刷新页面说配置文件为空,我也会收到错误消息。
我对 React 和生命周期方法非常陌生,非常感谢任何关于我做错了什么以及为什么 componentWillReceiveProps 被弃用的反馈。
提前致谢