组件渲染太早 [英] Component rendering too early

查看:74
本文介绍了组件渲染太早的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个PrivateRoute(HOC)来测试用户是否已经过身份验证(在redux存储中检查'auth'),然后再将它们发送到实际路由。问题是在我的auth出现在redux商店之前,privateroute完成了。

I am trying to create a PrivateRoute(HOC) to test if a user has been authenticated(check is 'auth' exist in redux store) before sending them to the actual route. The issue is the privateroute finishes before my auth shows up in redux store.

console.log运行两次,第一次,auth没有出现在商店中,但它第二次,但到那时,它已经将用户路由到登录屏幕....我怎样才能给予足够的时间来完成提取?当我只想有条件地显示某些内容时(比如登录/注销按钮),我知道如何处理这种情况,但是当尝试有条件地路由某人时,这种方法也不起作用。

The console.log runs twice, the first time, auth doesnt appear in the store, but it does the second time, but by that time, its already routed the user to the login screen.... How can I give enough time for the fetch to finish? I know how to do this condition when I simply want to display something conditionally(like login/logout buttons) but this same approach does not work when trying to conditionally route someone.

import React, { Component } from 'react'
import { connect } from 'react-redux'
import { Route } from 'react-router-dom'

class PrivateRoute extends Component {
  render() {
    const { component: Component, ...rest } = this.props
    console.log(this.props)

    return (
      <Route {...rest} render={(props) => (props.auth ? <Component {...props} /> : props.history.push('/login'))} />
    )
  }
}

function mapStateToProps({ auth }) {
  return { auth }
}

export default connect(mapStateToProps)(PrivateRoute)


推荐答案

当您的动作创建者返回令牌时,您需要将其存储在localStorage中。然后你可以像下面这样创建商店,

When your action creator return the token, you need to store it in localStorage. and then you can createstore like below,

const store = createStore(
    reducers,
    { auth: { authenticated : localStorage.getItem('token') }},
    applyMiddleware(reduxThunk)
)

如果用户已经登录,则令牌将在那里。初始状态将在商店中设置令牌,因此您无需调用任何操作创建者。

if user already logged in then token will be there. and initial state will set the token in store so you no need to call any action creator.

现在您需要通过检查用户是否已登录来保护您的组件。这是HOC的目的,

Now you need to secure your components by checking if user is logged in or not. Here's the HOC for do that,

import React, { Component } from 'react';
import { connect } from 'react-redux';

export default ChildComponent => {
  class ComposedComponent extends Component {

    componentDidMount() {
      this.shouldNavigateAway();
    }

    componentDidUpdate() {
      this.shouldNavigateAway();
    }
    shouldNavigateAway() {
      if (!this.props.auth) {
        this.props.history.push('/');
      }
    }
    render() {
      return <ChildComponent {...this.props} />;
    }
  }
  function mapStateToProps(state) {
    return { auth: state.auth.authenticated };
  }
  return connect(mapStateToProps)(ComposedComponent);
};

这篇关于组件渲染太早的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆