【问题标题】:ReactJS call API and RedirectReactJS 调用 API 和重定向
【发布时间】:2020-08-17 19:48:25
【问题描述】:

我在 ReactJs Redux 中遇到了一个问题,我正在尝试使用来自 Url 的 Token 调用 API。如果 API 请求失败,它会将 recoverPasswordToken 的状态更新为 false。我想在失败的情况下重定向到主页。在当前情况下,它不等待 API 响应并且 if 条件运行代表恢复密码令牌默认空值。

useEffect(() => {
        checkRecoverPasswordToken(match.params.token);
 if (!recoverPasswordToken) {
        console.log('working');
        return <Redirect to="/" />
    }
    }, []);

【问题讨论】:

    标签: reactjs redux react-redux use-effect


    【解决方案1】:

    我觉得你可以用history api代替重定向组件

    import {useHistory} from "react-router"
    //...
    
    const history = useHistory()
    
    useEffect(() => {
      checkRecoverPasswordToken(match.params.token).then(()=>{
         if (recoverPasswordToken) {
            history.push("/")
          }
       });
    }, []);
    

    【讨论】:

    • 当然。谢谢。重定向工作正常。我的问题与 API 调用上的 recoverPasswordToken 值更改有关。
    • 如果我理解你的话,如果 checkRecoverPasswordToken 是一个承诺,你也可以使用 history api
    • 非常感谢
    猜你喜欢
    • 2018-12-20
    • 2015-03-18
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-06
    • 1970-01-01
    相关资源
    最近更新 更多