无法从组件获取 redux 状态

问题描述 投票:0回答:1

我正在尝试获取 redux 状态(用户身份验证状态)。 我试图在

console.log
变量中
mapStateProps
它,但我得到的只是未定义。 我尝试从减速器中执行相同的操作,并在初始化变量后正确获取变量,但是当我将其传递给
AuthReducer
方法时,我根本没有得到输出,或者在 chrome redux dev- 中看到状态变量工具。

主函数 AuthReducer 似乎没有“看到”状态变量。

控制台:

AuthReducer.js:41 {isLoggedIn: false, accessToken: 'lalaa', username: '', email: '', exp: ''} (<==== right after initialization and before AuthReducer method)
App.js:50 {AuthReducer: ƒ, RegisterReducer: ƒ} 
App.js:51 undefined

AuthReducer.js:

import AuthTypes from "./AuthTypes"
// import axios from 'axios'

const authState = {
// const authState = {
    isLoggedIn: false, 
    accessToken: "lalaa", 
    username: "", 
    email: "", 
    exp: "", 
    // authorities: ["USER"]
}

// function getAuthState (state = authState) {
//     let token = sessionStorage.getItem('token')
//     let expiration = parseInt(sessionStorage.getItem('exp')) // originaly a string 
//     let loggedIn = sessionStorage.getItem('isLoggedIn')
//     try {       
//         if ( (new Date(expiration)) > new Date() ) {
//             console.log('not expired')
//             axios.defaults.headers.common["Authorization"] = `Bearer ${token}`
//             return {
//                 ...state, 
//                 accessToken: token,
//                 exp: expiration,
//                 isLoggedIn: loggedIn,
//             }
//         }
//         // console.log('in try')
//         return state
//     }
//     catch (error) {
//         console.log('in catch')
//         console.log('there was an error: ' + error)
//         return state
//     }
// }

// authState = getAuthState()
// const newAuthState = getAuthState()
console.log(authState)

const AuthReducer = (state = authState, action) => {
// const AuthReducer = (state = newAuthState, action) => {
    console.log('in reducer method')
    console.log(state)
    
    switch (action.type) {

        case AuthTypes.LOGIN_SUCCESS: {
            return {
                ...state,
                isLoggedIn: action.payload.isLoggedIn,
                accessToken: action.payload.accessToken,
                exp: action.payload.exp,
                // username: action.payload.username,
                // email: action.payload.email,
            }
        }

        case AuthTypes.LOGIN_FAIL: 
            return {
                ...state,
                isLoggedIn: false,
                accessToken: '',
                exp: 0,
                // username: action.payload.username,
                // email: action.payload.email,
            }

        default: return state
    }
}

export default AuthReducer

App.js:

// import {Redirect} from 'react-router-dom'
import './App.css'

import { BrowserRouter, Route, Switch } from 'react-router-dom' // Changed "BrowserRouter" in faivor of "Rotuer"
import { connect } from 'react-redux'
import axios from 'axios'
import { AuthActions } from './redux/Auth/AuthActions'


import Login from './pages/Login/Login'
import Register from './pages/Register/Register'

import Header from './components/Layout/Header/Header'
import Footer from './components/Layout/Footer/Footer'

// import store from './redux/store'
axios.defaults.baseURL=process.env.REACT_APP_API_URL // Set a default url for axios


const App = (props) => {

    return (
        <div className="App">
            <BrowserRouter>
                <Switch>
                    
                    <Route path='/test'>
                        <Header/>
                            Main
                        <Footer/>
                    </Route>

                    <Route exact path="/login"> 
                        <Login />
                    </Route>
                    
                    <Route exact path="/register">
                        <Register />
                    </Route> 
                
                </Switch>
            </BrowserRouter>

        
        </div>
    )
}

const mapStateToProps = (state) => {
    console.log(state)
    console.log(state.isLoggedIn)
    return {
        isLoggedIn: state.isLoggedIn,
    }
}

// const mapDispatchToProps = dispatch => {
//  return {
//      // authorized: true
//      authorized: () => {
//          dispatch(AuthActions())
//      }
//  }
// }

export default connect(
    mapStateToProps, 
    // mapDispatchToProps
)(App)

store.js:

import { createStore, compose, applyMiddleware } from 'redux'
// import { createStore} from 'redux'
import AuthReducer from './Auth/AuthReducer'
import RegisterReducer from './Register/RegisterReducer'
import thunk from 'redux-thunk'


const composeEnhancers = (typeof window !== 'undefined' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__) || compose
// const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose

const reducers = () => {
    return {
        AuthReducer, 
        RegisterReducer, 
        
    }
}

const store = createStore(
    reducers, 
    composeEnhancers(applyMiddleware(thunk)),
)

export default store

我最终想要完成的一些事情(只是为了确保这里的答案是相关的..): 我想检查用户是否已登录,以便我知道运行应用程序时要重定向。 (如果登录并访问 /login 页面,那么用户将被重定向到 /test 页面。反之亦然)。 在 AuthReducer.js 中有一个被注释掉的函数,它基本上从本地会话中获取数据并将其应用到 webapp 状态。

reactjs redux react-redux
1个回答
1
投票

我认为您没有正确访问mapStateToProps中的reducer,我将在您的商店设置中执行此操作以创建商店状态:

import { createStore, combineReducers, compose, applyMiddleware } from 'redux'
import AuthReducer from './Auth/AuthReducer'
import RegisterReducer from './Register/RegisterReducer'
import thunk from 'redux-thunk'

const composeEnhancers = (typeof window !== 'undefined' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__) || compose

// Combine the reducers using the combineReducers function to make it a big object containing the auth and register keys in this example.
const reducers = combineReducers({
    auth: AuthReducer, 
    register: RegisterReducer, 
});


const store = createStore(
    reducers, 
    composeEnhancers(applyMiddleware(thunk)),
)

export default store

现在在你的mapStateToProps函数中你需要这样调用它:

const mapStateToProps = (state) => ({
        // Look how it references the auth key I just made in the combineReducers function.
        isLoggedIn: state.auth.isLoggedIn,
});
© www.soinside.com 2019 - 2024. All rights reserved.