使用Redux获取组件上的商店价值

我有这个元素的商店:


loggedIn:false

我想做的是阻止用户尚未登录的任何页面。当他成功登录时,布尔值在其他组件上变为true。


为了阻止他访问应用程序的其他链接,我创建了一个名为Refresh Route的组件,该组件可以执行以下操作:


import React from "react";

import { connect } from "react-redux";

import { Route, Redirect } from "react-router-dom";


const RefreshRoute = ({ component: Component, ...rest }) => {

const canGo=this.props.loggedIn;

window.alert(canGo)

return (<Route

    {...rest}

    render={props =>

        canGo ? (

            <Component {...props} />

        ) : (

                <Redirect

                    to={{

                        pathname: "/login"

                    }}

                />

            )

    }

/>)

}


 const mapStateToProps = state => {

  return {

    loggedIn: state.atuth.loggedIn

 }

}


export default connect(mapStateToProps)(RefreshRoute); 

我的问题是道具为空,我不知道为什么。


这是我称为“刷新路线”的组件:


const Routes = () => (

 <main>

 <Switch>

  <Route exact path='/' component={Main} /> 

  <Route exact path='/customers' component={Customers} />

  <Route exact path='/customers/:market' component={CustomersByMarket} />

  <Route exact path='/customers/:market/:customer' component={Customer} />

  <Route exact path='/customers/:market/:customer/:environment' component={MessageDashboard} />

  <RefreshRoute exact path='/home' component={Main}/>

  <Route exact path='/addPermission' component={AddPermissions}/>

  <Route exact path='/excludePermission' component={RemovePermissions}/>

  <Route exact path='/login' component={SignIn}/>

</Switch>


导出默认路由;


慕桂英4014372
浏览 125回答 2
2回答

富国沪深

问题在这里:const RefreshRoute = ({ component: Component, ...rest }) => {&nbsp; &nbsp; const canGo=this.props.loggedIn;您正在props使用破坏输入{ component: Component, ...rest }。因此,该属性loggedIn将位于其中rest.loggedIn:const RefreshRoute = ({ component: Component, ...rest }) => {&nbsp; &nbsp; const canGo = rest.loggedIn;否则,您可以loggedIn在分解后的参数内部显式并使用它:const RefreshRoute = ({ component: Component, loggedIn, ...rest }) => {&nbsp; &nbsp; const canGo = loggedIn;

炎炎设计

因此,在功能组件中您无需this.props更改:const RefreshRoute = ({ component: Component, ...rest }) => {&nbsp;&nbsp; const canGo=this.props.loggedIn; // props is not bound to this&nbsp; ...}至:const RefreshRoute = (props) => {&nbsp;&nbsp; const canGo = props.loggedIn}或您的情况:const RefreshRoute = ({ component: Component, ...rest }) => {&nbsp; const canGo = rest.loggedIn}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript