无法从组件中获取 redux 状态
Cannot fetch redux state from component
我正在尝试获取 redux 状态(用户身份验证状态)。
我试图在 mapStateProps
变量中 console.log
它,但我得到的只是未定义的。
我尝试从 reducer 做同样的事情,并在初始化后正确获取变量,但是当我将它传递给 AuthReducer
方法时,我根本没有得到输出,或者看到 [= 中的状态变量35=] redux 开发工具。
似乎主要功能 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 状态。
我认为您没有正确访问 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,
});
我正在尝试获取 redux 状态(用户身份验证状态)。
我试图在 mapStateProps
变量中 console.log
它,但我得到的只是未定义的。
我尝试从 reducer 做同样的事情,并在初始化后正确获取变量,但是当我将它传递给 AuthReducer
方法时,我根本没有得到输出,或者看到 [= 中的状态变量35=] redux 开发工具。
似乎主要功能 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 状态。
我认为您没有正确访问 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,
});