我正在维护react redux应用程序并尝试对应用程序中的其中一条路线进行身份验证,即/dashboard
。我想将一个布尔状态从redux存储传递给一个名为authed
的道具但是很难...当前,我只是将true
值作为伪值传递。
import React from 'react'
import {
HashRouter,
Route,
Link,
Switch,
Redirect
} from 'react-router-dom'
// components that are main pages
import Home from './containers/Home'
import Login from './containers/Login'
import Signup from './containers/Signup'
import NotFound from './containers/NotFound'
import Dashboard from './containers/Dashboard'
import IntersectionForm from './containers/IntersectionForm'
import IntersectionDetail from './containers/IntersectionDetail'
import { connect } from 'react-redux'
const PrivateRoute = ({component: Component, authed, ...rest}) => {
return (
<Route
{...rest}
render={(props) => authed === true
? <Component {...props} />
: <Redirect to={{pathname: '/', state: {from: props.location}}}/>}
/>
)
}
function mapStateToProps (state) {
return state
}
const PrivateRouteContainer = connect(mapStateToProps)(PrivateRoute)
const Routes = (history) => {
return (
<HashRouter history={history}>
<switch>
<Route exact path="/" component={Login}/>
<Route exact path="/signup" component={Signup}/>
<PrivateRouteContainer authed={true} path='/dashboard' component={Dashboard}/>
</switch>
</HashRouter>
)
}
export default Routes
答案 0 :(得分:0)
function mapStateToProps (state) {
return state
}
通过这样做,您的组件将获得包含reducers中所有状态的道具。
例如,如果你有:
import { combineReducers } from 'redux'
import todos from './todos'
import counter from './counter'
export default combineReducers({
todos,
counter
})
然后,您的PrivateRoute
会获得todos
和counter
道具。
这就是为什么如果你的mapStateToProps
抓住它需要的道具,它会更好。
function mapStateToProps (state) {
return {
authed: state.nameOfReducer.isAuthed, // or whetever is the value you need to know if user is authorized
}
}
但是,如果你不是combineReducers
并且你的应用中只有一个减速器,那么:
function mapStateToProps (state) {
return {
authed: state.isAuthed,
}
}
答案 1 :(得分:0)
从componentDidMount函数调用auth_actions中的auth端点(POST)。
在actioncreator中获得响应后发送操作。
- 例如:isAuthenticated:true / false并返回有效负载。
通过使您的反应组件连接并在其中来访问该值 组件的mapStatetoprops,您可以访问此布尔值 value - 使用this.props.authValue。