Auth.js
import React, { Component } from 'react'
import { Redirect } from 'react-router-dom'
import { connect } from 'react-redux'
import { login } from './Auth.redux'
// @connect(
// state => state.auth,
// {login}
// )
class Auth extends Component{
render(){
return(
<div>
{this.props.isAuth ? <Redirect to='/dashboard' /> : null}
<p>你没有权限查看,需要登录</p>
<button onClick={this.props.login}>登录</button>
</div>
)
}
}
const mapStateToProps = state => {
return {
auth: state.auth
}
}
const authCreators = {login}
export default connect(mapStateToProps, authCreators)(Auth)
// export default Auth
当我单击button
时,如果dashboard
为login
,我想从isAuth
重定向到true
。
现在,isAuth
是true
,但是页面未重定向到dashboard
,我找不到原因。
我以为是,当单击button
时,调用login()
,login()
是Auth.redux actionCreators,因为actionCreators返回的操作类型是LOGIN
,然后调度login
操作
Auth.redux.js
const LOGIN = 'login'
const LOGOUT = 'logout'
const initialState = {
isAuth: false,
username: 'ok'
}
export function auth(state=initialState, action){
//console.log(state)
switch(action.type){
case LOGIN:
return {...state, isAuth: true}
case LOGOUT:
return {...state, isAuth: false}
default:
return state
}
}
export function login(){
return {type: LOGIN}
}
export function logout(){
return {type: LOGOUT}
}
dashboard.js
import React, { Component } from 'react'
import { Link, Route, Redirect } from 'react-router-dom'
import { connect } from 'react-redux'
import App from './App'
import {logout} from './Auth.redux'
function Two(){
return <h2>two</h2>
}
function Three(){
return <h2>Three</h2>
}
// @connect(
// state => state.isAuth,
// {logout}
// )
class Dashboard extends Component{
render(){
const redirectLogin = <Redirect to='/login'/>
const app = (
<div>
<ul>
<li>
<Link to='/dashboard/'>one</Link>
</li>
<li>
<Link to='/dashboard/two'>two</Link>
</li>
<li>
<Link to='/dashboard/three'>three</Link>
</li>
</ul>
<Route exact path='/dashboard/' component={App}></Route>
<Route path='/dashboard/two' component={Two}></Route>
<Route path='/dashboard/three' component={Three}></Route>
</div>
)
return this.props.isAuth ? app : redirectLogin
}
}
const mapStateToProps = state => {
return {
auth: state.auth
}
}
const actionCreators = {logout}
export default connect(mapStateToProps, actionCreators)(Dashboard)
答案 0 :(得分:0)
在Auth
和Dashboard
组件中,您检查了this.props.isAuth
,但它将返回undefined
,因为只有auth
道具引用了{{1 }}。
因此,您需要检查state.auth
验证是正确还是错误。