Reactjs 更新反应子组件';使用从父组件中进行的异步api调用接收到的道具来恢复状态

Reactjs 更新反应子组件';使用从父组件中进行的异步api调用接收到的道具来恢复状态,reactjs,state,lifecycle,react-props,Reactjs,State,Lifecycle,React Props,我想做的是使用道具设置我的状态,但问题是我的道具来自父组件中的api调用(我使用的是react router dom)。所以首先我尝试使用componentDidMount,当您从欢迎页面(Child)转到主页(Child)时,它可以工作,但是当您直接来到主页时,componentDidMount会在api调用之前填充状态(基本上未定义) 接下来,我尝试使用componentDidUpdate,它在您直接进入主(子)页面时有效,但当您从欢迎页面(子)进入主(子)页面时,componentDidU

我想做的是使用道具设置我的状态,但问题是我的道具来自父组件中的api调用(我使用的是react router dom)。所以首先我尝试使用componentDidMount,当您从欢迎页面(Child)转到主页(Child)时,它可以工作,但是当您直接来到主页时,componentDidMount会在api调用之前填充状态(基本上未定义)

接下来,我尝试使用componentDidUpdate,它在您直接进入主(子)页面时有效,但当您从欢迎页面(子)进入主(子)页面时,componentDidUpdate甚至不会启动。(再次未定义)(componentDidUpdate在组件初始化时不会运行,即第一次创建组件时) 另外,如果您导航到另一条路线并返回,它在componentDidUpdate的情况下不起作用我认为组件生命周期从一开始就开始了,有人能确认一下吗??

现在我在代码中同时使用了componentDidUpdate和componentDidMount,它运行良好。我只是想知道这是最好的方法还是有其他方法可以使用api调用中的道具来填充状态

主分量

constructor(props: HomeProps) {
    super(props);
    this.state = {
      myUser: {},
    }
  }


  componentDidUpdate = (prevProps: HomeProps) => {
    if (prevProps.userProfile.ID !== this.props.userProfile.ID) {
      this.setState({ myUser: this.props.userProfile });
    }
  }

componentDidMount = () => {
    this.setState({ myUser: this.props.userProfile })
  }
主要组件(父级) 欢迎:path=“/” Home:path=“/Home”


()} />
()} />

只是想知道正确的方法,如果你能解释为什么更好的话,我也会感激的。

< P>我会这样做,而不是把不同的路径当成亲子,我会把它们看成是平行的或兄弟姐妹的。在这种情况下,我将使用Redux或您首选的状态管理。随着你的应用程序的增长和你添加更多的路由,你必须将用户道具从你的父路由传递到所有未来的路由,这将是一个更大的问题来维护


使用Redux这样的状态管理工具,所有组件都可以访问状态,无需向每个组件传递道具,无论路由有多深或添加了多少兄弟路由。

首先,你应该使用async/await api调用,如果你在api中使用async/await,你可以使用下面的方法来解决这个问题

   constructor(props: HomeProps) {
        super(props);
        this.state = {
          myUser: {},
        }
      }        
      componentDidUpdate = async(prevProps: HomeProps) => {
        if (prevProps.userProfile.ID !== this.props.userProfile.ID) {
        await  this.setState({ myUser: this.props.userProfile });
        }
      }        
   componentDidMount = async () => {
       await this.setState({ myUser: this.props.userProfile })
      }

家不是受欢迎的孩子。他们都在同一级别,只有一个会由于切换而呈现。是的,他们是,我已经更新了问题,并将登陆改为欢迎
   constructor(props: HomeProps) {
        super(props);
        this.state = {
          myUser: {},
        }
      }        
      componentDidUpdate = async(prevProps: HomeProps) => {
        if (prevProps.userProfile.ID !== this.props.userProfile.ID) {
        await  this.setState({ myUser: this.props.userProfile });
        }
      }        
   componentDidMount = async () => {
       await this.setState({ myUser: this.props.userProfile })
      }