我正在重构我的React应用程序。我想用getDerivedStateFromProps替换componentWillRecieveProps。由于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
});
}
}
答案 0 :(得分:1)
应从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;
}
答案 1 :(得分:0)
您可能不需要派生状态,可以为此使用componentDidUpdate()方法。与getDerivedStateFromProps不同,这不是静态的,因此您应该可以使用this.setState()。