Javascript 使用getDerivedStateFromProps访问状态集

Javascript 使用getDerivedStateFromProps访问状态集,javascript,reactjs,Javascript,Reactjs,我试图了解这个新的生命周期方法(getDerivedStateFromProps)在react中是如何工作的,我不确定为什么在使用此方法设置状态字段后无法访问它。 我会解释我的意思 声明: this.state = { status: "Activ", currPage: "1", favorites: [], profileType: "" }; 下面是比较nextProps和prevState的方法,返回设置状态的对象。这工作正常,状态设置正确 static getDeri

我试图了解这个新的生命周期方法(getDerivedStateFromProps)在react中是如何工作的,我不确定为什么在使用此方法设置状态字段后无法访问它。 我会解释我的意思

声明:

this.state = {
  status: "Activ",
  currPage: "1",
  favorites: [],
  profileType: ""
};
下面是比较nextProps和prevState的方法,返回设置状态的对象。这工作正常,状态设置正确

static getDerivedStateFromProps(nextProps, prevState) {
  if (nextProps.profile) {
    if (nextProps.profile !== prevState.profileType) {
      return { profileType: nextProps.profile.profile.profileType };
    }
  }

  return null;
}

接下来,在componentDidMount()中,我尝试从状态记录profileType。据我所知,这个方法是在getDerivedStateFromProps之后调用的,因此,现在应该设置状态了

componentDidMount() {
  this.props.getCurrentProfile();
  console.log("Profile Type is: " + this.state.profileType);
}
尽管如此,记录这一点,还是会给我
未定义的


我在这里做错了什么?

您确定在初始渲染时设置了
nextrops.profile
?没有明显的问题。:/确保
getCurrentProfile
render
根本不会影响状态。(任何地方的意外
this.state.profileType=undefined
都会导致此问题。)