我正在嘗試將redux-auth-wrapper整合到反應樣板中。React,Redux和身份驗證 - 找不到狀態
根據我的調試工具,瀏覽器的狀態設置正確(用戶:{data:null,isLoading:false}),但是應用程序說狀態是未定義的。
mapStateToProps似乎是正確的狀態?
減速機:
容器/應用/ reducer.js:
import { fromJS } from 'immutable';
import {
USER_LOGGING_IN,
USER_LOGGED_IN,
USER_LOGGED_OUT,
} from '../../constants';
const userInitialState = fromJS({
data: null,
isLoading: false,
});
function userReducer(state = userInitialState, action) {
switch (action.type) {
case USER_LOGGING_IN:
return state
.set('isLoading', true);
case USER_LOGGED_IN:
return state
.set('data', action.payload)
.set('isLoading', false);
case USER_LOGGED_OUT:
return userInitialState;
default:
return state;
}
}
export default userReducer;
容器/應用/ index.js
import React from 'react';
import { Route, NavLink } from 'react-router-dom';
import { connect } from 'react-redux';
import { logout } from '../../actions/user';
import Home from '../../components/Home';
const getUserName = (user) => {
if (user.data) {
return `Welcome ${user.data.name}`;
}
return ('Not logged in');
};
const UserName = ({ user }) => (<div>{getUserName(user)}</div>)
function App({ user, logout }) {
return (
<div>
<h1>Test App</h1>
<div>
<nav>
<NavLink exact to="/">Home</NavLink>
</nav>
<nav>
</nav>
<div>
<Route exact path="/" component={Home} />
</div>
</div>
</div>
);
}
const mapStateToProps = (state) => ({
user: state.user, -- this is undefined when it should not be
});
export default connect(mapStateToProps, { logout })(App);
reducers.js:
/**
* Combine all reducers in this file and export the combined reducers.
*/
import { fromJS } from 'immutable';
import { combineReducers } from 'redux-immutable';
import { LOCATION_CHANGE } from 'react-router-redux';
import languageProviderReducer from 'containers/LanguageProvider/reducer';
import userReducer from 'containers/App/reducer';
/*
* routeReducer
*
* The reducer merges route location changes into our immutable state.
* The change is necessitated by moving to [email protected]
*
*/
// Initial routing state
const routeInitialState = fromJS({
location: null,
});
/**
* Merge route into the global application state
*/
function routeReducer(state = routeInitialState, action) {
switch (action.type) {
/* istanbul ignore next */
case LOCATION_CHANGE:
return state.merge({
location: action.payload,
});
default:
return state;
}
}
/**
* Creates the main reducer with the dynamically injected ones
*/
export default function createReducer(injectedReducers) {
return combineReducers({
route: routeReducer,
language: languageProviderReducer,
user: userReducer,
...injectedReducers,
});
}
這僅僅是發生反應的樣板,但混合與反應路由器4的例子(auth.js,constants.js,應用/ reducer.js,應用/ index.js等)
謝謝,我實施這個稍有不同(使用選擇器),但不使用.toJS()是問題! – Codematcha
沒問題,先生☺ –