我可以调度状态,但是在redux中访问它会遇到问题
import React, {useEffect} from 'react';
import AuthenticationPage from './AuthenticationPage';
import '../styles/App.css';
import SignOut from './SignOut';
import{TOGGLE_LOGIN} from "../redux/actionTypes"
import{connect} from 'react-redux'
function App(props) {
useEffect(()=>{
if(window.localStorage.getItem('IsUserLogged')==="true"){
props.toggleLogin();
}
console.log(props.isLogged); //console show undefined
},[])
return (
<div className="App">
{props.isLogged===true?
<SignOut/>:
<AuthenticationPage/>}
</div>
);
}
const mapStateToProps = state =>{
return{
isLogged: state.isLogged
}
}
const mapDispatchToProps = dispatch=>{
return{
toggleLogin: ()=>dispatch({type: TOGGLE_LOGIN})
}
}
export default connect(mapStateToProps, mapDispatchToProps)(App);
来切换状态
但是当我尝试使用props.isLogged获取状态值时,它将返回undefined而不是true / false。
这是我的redux代码:
reducers / logIn.js
import{TOGGLE_LOGIN} from "../actionTypes"
const initialState={
isLogged: false,
}
const LogInReducer = (state=initialState, action)=>{
switch(action.type){
case TOGGLE_LOGIN:{
return Object.assign({}, state, {
isLogged: !state.isLogged
})
}
default:{
return state;
}
}
}
export default LogInReducer;
reducers / index.js
import{combineReducers} from "redux";
import LogInReducer from './logIn.js';
export default combineReducers({
LogInReducer
})
actions.js
import{TOGGLE_LOGIN} from "./actionTypes"
export const ToggleLogin=()=>({
type: TOGGLE_LOGIN
});
actionTypes.js
export const TOGGLE_LOGIN="TOGGLE_LOGIN";
});
store.js
import {createStore} from 'redux';
import rootReducer from './reducers';
export default createStore(rootReducer, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());
答案 0 :(得分:2)
那是因为在您的combineReducer
中,您有一个LogInReducer
键。
所以状态实际上是LogInReducer.isLogged
(在redux-dev-tool屏幕截图中也可以看到)。
您可能想要这样做:
const mapStateToProps = state => {
const { isLogged } = state.LogInReducer;
return {
isLogged
};
}