繁体   English   中英

React生命周期方法,用于在重新渲染组件时进行API调用

[英]React life cycle method for making API call when component is re-rendered

我有一个名为<Header>的组件,其中有一个登录表单,该表单进行API调用来登录用户。

标头组件中有一个函数,该函数可以成功登录后进行一些API调用以获取一些数据并更新标头中的菜单项:

componentDidMount() {
        const { auth, actions, children } = this.props;;
        if (auth.isLoggedIn) {
            actions.getAssessmentRequest();
            actions.getFirstSubsectionRequest();
        }
    }

我遇到的问题是,用户首次登录上述componentDidMount函数时不会触发,因为页眉组件是在第一次加载页面时已经安装的。

我尝试使用componentDidUpdatecomponentWillReceiveProps但是它们被多次触发,并且出现请求超时错误。

有什么想法可以使用哪种生命周期方法来实现?

是的,您在正确的道路上,应该使用componentWillReceiveProps生命周期方法。 防止无限循环并不断发出请求的技巧是,您必须执行检查以测试您关心的道具是否实际发生了变化:

componentDidMount() {
    this.fetchData(this.props);
}

componentWillReceiveProps(nextProps) {
    if(nextProps.auth.isLoggedIn !== this.props.auth.isLoggedIn) {
        this.fetchData(nextProps);
    }
}

fetchData(props) {
    const { auth, actions, children } = props;
    if (auth.isLoggedIn) {
        actions.getAssessmentRequest();
        actions.getFirstSubsectionRequest();
    }
}

我不能告诉你为什么要多次调用它,但是我可以告诉你这没关系。 问题在于您没有针对变化的道具进行比较。 如果这样做,代码将按照您想要的方式运行:

componentWillReceiveProps(newProps) {
  const { auth, actions, children } = newProps;
  if (auth.isLoggedIn !== this.props.auth.isLogin) {
    actions.getAssessmentRequest();
    actions.getFirstSubsectionRequest();
  }
}

另请参阅官方的ReactJS文档,该文档指出: https ://facebook.github.io/react/docs/react-component.html#componentwillreceiveprops

希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM