代码之家  ›  专栏  ›  技术社区  ›  Nespony

只在react中运行一次函数?

  •  1
  • Nespony  · 技术社区  · 6 年前

    我有一个React Redux项目。我有以下方法:

    const UmvValidator = (actions) => {
        const expiryTime = localStorage.getItem('expiryTime')
        const currentTime = moment().valueOf()
        if (expiryTime) {
            if (expiryTime.valueOf() > currentTime) {
                localStorage.clear('expiryTime')
    
            }
        } else {
            actions.directToLogin()
        }
    }
    

    actions.directtologin()如下所示:

    export function directToLogin() {
        return function (dispatch) {
            dispatch(push('/'));
        }
    }
    

    我想运行这个方法一次,当我的组件第一次像这样呈现时:

    componentWillMount() {
            const { actions } = this.props
             umvValidator(actions)
        }
    

    其想法是,如果到期时间晚于当前时间,用户将被重定向到主页。这类工作-用户从一个页面指向主页。然而,由于umvvalidator不断被调用,主页继续在主页和原始页之间闪烁!

    我不知道该怎么解决,谢谢你的帮助!

    2 回复  |  直到 6 年前
        1
  •  0
  •   Oleksandr Maliuta    6 年前

    像这样?

     const UmvValidator = (actions) => {
            const expiryTime = localStorage.getItem('expiryTime');
            const init = localStorage.getItem('init');
            const currentTime = moment().valueOf()
            if (expiryTime && !init) {
                if (expiryTime.valueOf() > currentTime) {
                    localStorage.clear('expiryTime')
    
                }
            } else {
                localStorage.setItem('init',1)
                actions.directToLogin()
            }
        }
    
        2
  •  0
  •   Sylvain    6 年前

    您的组件一直安装和卸载是不正常的。这就是问题所在。一旦你修复了这个,它将只安装一次 UmvValidator 函数只能调用一次。

    因为我在您的示例中看到了与路由相关的代码,所以我怀疑您的组件可能是 里面 你的孩子 router 视图元素(我不知道您在使用什么)。因此,每次组件调用actions.directtologin()时,路由都会更改,并创建同一组件的新实例,然后再次唤醒,在循环中调用umvvalidator。

    所以不是:

    <div>
      <routerView>
        <MyComponent/>
        <OtherStuff>
      </routerView>
    </div>
    

    做:

    这只是用来说明我所说内容的伪代码。

    另一个原因可能是,您有条件地使用一个变化很大的条件呈现组件,并导致组件装载和卸载:

    render(){
      return (
           <div>
           {conditionThatChangesALot && <MyComponent/>}
           </div>
      )
    }    
    

    我希望这有帮助