我正在重构我的反应性应用程序。我想用componentWillRecieveProps代替getDerivedStateFromProps。由于getDerivedStateFromProps不支持setState,所以我只能使用下面的代码。如何将其转换为getDerivedStateFromProps?
componentWillReceiveProps(nextProps) {
if (nextProps.errors) {
this.setState({ errors: nextProps.errors });
}
if (nextProps.profile.profile) {
const profile = nextProps.profile.profile;
profile.company = !isEmpty(profile.company) ? profile.company : '';
profile.website = !isEmpty(profile.website) ? profile.website : '';
profile.location = !isEmpty(profile.location) ? profile.location : '';
// Set component fields state
this.setState({
company: profile.company,
website: profile.website,
location: profile.location
});
}
}发布于 2019-02-14 07:30:57
更新后的状态应该从getDerivedStateFromProps钩子返回。如果不应该更新状态,则返回null:
static getDerivedStateFromProps(nextProps) {
if (nextProps.errors) {
return { errors: nextProps.errors };
}
if (nextProps.profile.profile) {
const profile = nextProps.profile.profile;
profile.company = !isEmpty(profile.company) ? profile.company : '';
profile.website = !isEmpty(profile.website) ? profile.website : '';
profile.location = !isEmpty(profile.location) ? profile.location : '';
return {
company: profile.company,
website: profile.website,
location: profile.location
};
}
return null;
}发布于 2019-02-14 05:26:30
您可能不需要派生状态,为此可以使用componentDidUpdate()方法。与getDerivedStateFromProps不同,这不是静态的,因此您应该能够使用this.setState()。
https://stackoverflow.com/questions/54683607
复制相似问题