【问题标题】:Call function after history.push() redirectshistory.push() 重定向后调用函数
【发布时间】:2020-12-22 20:40:27
【问题描述】:

我有一个函数可以检查用户是否在 componentDidMount 上登录,如果有会话,则将登录按钮更改为注销。

问题:

我尝试使用 ComponentdidUpdate,但由于该组件已安装并且我无法更新状态,因此它不会刷新,因此我的登录按钮保持为登录按钮。

componentDidMount() {
        Axios.get(config.ServerURL + "/user", {withCredentials: true}).then(result => {
            console.log("component mounted:",result.data)
            if (result.data) {
                this.setState({isLoggedIn: true});
            }
        }).catch(error => {
            console.log({message: error.response});
        })
    }

我有一个根据状态改变的按钮:isLoggedIn:

<div className={"App-login-button"}>
                                {!this.state.isLoggedIn && <Link to={"/login"}>
                                    <AwesomeButton type="primary" title={"Login"}>Login</AwesomeButton>
                                </Link>}

                                {this.state.isLoggedIn && <Link to={"/logout"}>
                                    <AwesomeButton type="primary" title={"logout"} onPress={this.handleLogOut}>logout</AwesomeButton>
                                </Link>}

                            </div>

当我从我的登录组件登录时(例如:localhost:3000/login)

handleSubmit = (event) => {
        Axios.post(Config.ServerURL + '/auth/login',
            {email: this.state.email, password: this.state.password},
            {
                withCredentials: true

            }).then(result => {
            if (result.data.business) {
                this.props.history.push({pathname: '/business', state: {email: result.data.email}});
            }
            useHistory.push('/', );

        }).catch(error => {
            console.log(error);
            //console.log(error.response.data.info)
        });

    }

为用户

exports.find = (req, res) => {
    res.send(req.user);
}

我愿意:

将 state.isLoggedIn 更改为 true

再次运行获取用户检查。

【问题讨论】:

  • 在您的 componentDidMount 函数中,您正在调用 API,当它给出响应时,您正在更新状态。现在,当状态更新时,应该再次调用渲染函数,因此它应该显示所需的行为。你能再解释一下你的问题吗?
  • 当我返回登录页面 (App.js) 时,我从不同的组件页面 (Login.js) 登录,我的应用程序组件未从 history.push() 更新。因此,从 App.js 显示的我的按钮不会从 login.js 的更改中更新
  • 在您的 componentDidMount 中,您调用了一个 get api,但是用于检查该特定用户是否登录的用户数据(如电子邮件(唯一的东西))在哪里?
  • 您是否尝试在您的 .then 方法中运行一些 console.log,因为您的状态没有得到更新,或者您的 api 无法正常工作,因此发生了这个问题
  • 如果有req.user,GET调用将在result.data中有对象。因此,设置为已登录的状态为真。我的状态在第一次进入页面时得到更新。问题是这条逻辑之路。未登录:(显示登录按钮)。按 LOGIN -> 登陆页面组件路由到登录组件。在 LOGIN COMPONENT 中输入凭据。登录组件路由到登录页面。 (显示登录按钮)。因为登陆页面没有再次运行get函数,所以显示的是LOGIN按钮而不是LOGOUT按钮。

标签: reactjs react-router


【解决方案1】:

我变了

useHistory.push('/');

返回

this.props.history.push('/');
this.props.history.go();

go 强制刷新页面,允许组件重新渲染。我不介意增加的计算问题,所以这对我有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-23
    • 2018-07-15
    • 1970-01-01
    • 2019-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多