【问题标题】:map redux state to prop in authenticated react route component将 redux 状态映射到经过身份验证的反应路由组件中的道具
【发布时间】:2020-06-10 01:34:17
【问题描述】:

我试图创建一个经过身份验证的路由组件来包装我的反应路由,如果登录无效,它会重定向到“/”路径。我在关注这个答案:https://stackoverflow.com/a/43171515/6716062

但是我想访问我的 redux 商店。如何访问我想注入道具的 loginStatus 道具?使用以下代码 props.loginStatus 未定义

谢谢

import React from 'react';
import { Route, Redirect } from 'react-router-dom';
import { SUCCESS } from '../common/webUtils';
import { connect } from 'react-redux';

function AuthRoute( {component: Component, ...rest} ) {
  return (
    <Route
      {...rest}
      render={ (props) => props.loginStatus === SUCCESS
      ? <Component {...props} />
      : <Redirect to={{pathname: '/', state: {from: props.location}}} />}
  />
  )
}

function mapStateToProps( state ) {
  return {
    loginStatus: state.userReducer.loginStatus
  }
}

export default connect( mapStateToProps )( AuthRoute ); 

【问题讨论】:

  • loginStatus 未在 AuthRoute 道具中传递。如果你添加它应该可以工作。
  • 您可以使用选择器从 redux 商店访问道具,但您需要像 @alewis729 提到的那样传递它们

标签: javascript reactjs redux react-router-dom


【解决方案1】:

正确的道具对象访问loginStatus,在本例中为rest,包含从connect HOC 传递的loginStatus 道具。您还可以稍微考虑一下代码以检查 outside 返回的内容。 Route 仅将route-props 传递给componentrenderchildren

function AuthRoute( {component: Component, loginStatus, ...rest} ) {
  const authenticated = loginStatus === SUCCESS;
  return (
    <Route
      {...rest}
      render={(routeProps) => authenticated
        ? <Component {...routeProps} />
        : <Redirect to={{pathname: '/', state: {from: props.location}}} />
      }
  />
  )
}

function mapStateToProps( state ) {
  return {
    loginStatus: state.userReducer.loginStatus
  }
}

export default connect( mapStateToProps )( AuthRoute );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-26
    • 2019-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-07
    • 1970-01-01
    • 2023-03-09
    相关资源
    最近更新 更多