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

时间:2018-03-27 15:30:55

标签: javascript reactjs react-redux

我有一个名为<Header>的组件,我有一个登录表单,可以进行API调用以记录用户。

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

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

我遇到的问题是用户第一次登录上面的componentDidMount函数时没有触发,因为第一次加载页面时已经挂载了标题组件。

我尝试使用componentDidUpdatecomponentWillReceiveProps但是它们被多次触发,我收到请求超时错误。

我可以用什么生命周期方法来实现这个目标?

2 个答案:

答案 0 :(得分:3)

是的,您走在正确的道路上,您应该使用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();
    }
}

答案 1 :(得分:0)

我不能告诉你为什么它被多次调用,但我可以告诉你它应该没关系。问题是你没有比较道具的变化。如果您这样做,代码将按您希望的方式运行:

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

希望这有帮助。

相关问题