这很难解释,但是我有一个父组件Profile,其中有许多Profile-info子级。子级具有输入,提交后调用子级Profile中的方法以更新Profle状态的值。 “用户”状态对象是在Axios调用的响应中更新的,但是当触发getDerivedStateFromProps时,nextProps具有旧的用户对象。当在完成用户查找时加载应用程序,然后从应用程序更新道具时,getDerivedStateFromProps可以正常工作,然后在Profile中填充该道具。我不太确定为什么要在这里调用它,因为Profile中不应该有任何甚至在变化的道具?有帮助吗?
static getDerivedStateFromProps(nextProps, prevState) {
if (nextProps.user !== prevState.user) {
return {
user: nextProps.user
};
} else {
return null;
}
}
updateUser(field) {
const personalInfo = {};
const corporateInfo = {};
const merged = { ...this.state.user, ...field };
const headers = { headers: { Authorization: "Bearer " + getToken() } };
Axios.put(
getServerUrl() + "api/Employees/" + this.state.user.employeeId,
merged,
headers
)
.then(response => {
console.log(response);
if (response.status === 200 || response.status === 204) {
Object.keys(this.state.personalInfo).map(
k => (personalInfo[k] = merged[k])
);
Object.keys(this.state.corporateInfo).map(
k => (corporateInfo[k] = merged[k])
);
//this.props.user = merged;
this.setState({
personalInfo: personalInfo,
corporateInfo: corporateInfo,
isLoading: false,
successMessage: "Successfully updated employee",
user: merged
});
} else {
this.setState({
validationError: response.data.message
? response.data.message
: "Error editing account",
isLoading: false
});
}
})
.catch(error => {
this.setState({
validationError: "Error editing account",
isLoading: false
});
});
console.log("Update user setState", this.state);
}