【问题标题】:Cannot fetch redux state from component无法从组件中获取 redux 状态
【发布时间】:2021-11-23 19:32:18
【问题描述】:

我正在尝试获取 redux 状态(用户身份验证状态)。 我试图在mapStateProps 变量中使用console.log 它,但我得到的只是未定义的。 我尝试从减速器中执行相同的操作,并且在初始化它后正确地获取了变量,但是当我将它传递给 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 redux-thunk redux-store


    【解决方案1】:

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

    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,
    });
    

    【讨论】:

      猜你喜欢
      • 2021-11-29
      • 1970-01-01
      • 1970-01-01
      • 2021-07-09
      • 2019-03-20
      • 2022-06-24
      • 2021-04-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多