我有两个redux状态变量,一个保存用户信息数组,另一个保存侧面抽屉打开/关闭功能的true / false值。 true / false值触发className更改,该更改触发CSS打开/关闭抽屉。用户信息数组是从Firebase云Firestore数据库集合中获取的。
由于某种原因,在获取用户数组并将其保存为redux状态,并且用户打开侧抽屉后,发送的redux操作仅适用于侧抽屉,但是侧抽屉和用户信息已更改。
侧部抽屉正常打开,但用户数组设置为null。
Redux活动:
侧面抽屉组件
class SideDrawer extends Component {
render() {
let drawerClasses = ['side-drawer'];
if (this.props.toggled) {
drawerClasses = ['side-drawer', 'open'];
}
return (
<div className={drawerClasses.join(' ')} >
<div className="side-drawer-container" >
<div className="router-login-button" onClick={this.props.toggleSideDrawer} >
<OktaAuthButton />
</div>
<div className="side-drawer-link" onClick={this.props.toggleSideDrawer} >
<Link to="/" >Map</Link>
</div>
<div className="side-drawer-link" onClick={this.props.toggleSideDrawer} >
<Users />
</div>
</div>
</div>
)
}
}
const mapStateToProps = ({ sideDrawer }) => ({
toggled: sideDrawer.toggled,
});
const mapDispatchToProps = (dispatch) => {
return {
toggleSideDrawer: () => dispatch({ type: TOGGLE_SIDEDRAWER, payload: true })
}
}
export default connect(mapStateToProps, mapDispatchToProps)(SideDrawer);
侧抽屉减速器
import { TOGGLE_SIDEDRAWER } from './actions';
const initialState = {
toggled: false
};
export default function sideDrawerReducer(state = initialState, action) {
switch (action.type) {
case TOGGLE_SIDEDRAWER:
return Object.assign({}, state, {
toggled: action.payload
});
default:
return state;
}
}
用户组件
class Users extends Component {
/* commented code not needed to be shown */
componentDidMount() {
initializeFirebaseApp();
// Get user list from firestore 'users' collection
this.loadUsers();
}
async loadUsers() {
getAllUsers().then((users) => {
this.props.setUsers(users);
});
}
render() {
if(this.props.users != null) {
var users = this.props.users.map((el, i) => (
<li key={el.id} className='user' onClick={this.props.toggleSideDrawer}><Link to={"/user/" + el.id}>{el.firstname}</Link></li>
));
console.log(users);
}
console.log(this.props.users);
return (
<div className="user-container">
{users}
</div>
)
}
}
const mapStateToProps = ({ users }) => ({
users: users.friends
});
const mapDispatchToProps = (dispatch) => {
return {
setUsers: (users) => dispatch({type: SET_FRIENDS, payload: users}),
toggleSideDrawer: () => dispatch({ type: TOGGLE_SIDEDRAWER, payload: false })
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Users);
Users Reducer
import { SET_FRIENDS } from './actions';
const initialState = {
friends: null,
groups: null
};
export default function userReducer(state = initialState, action) {
switch(action.type) {
case SET_FRIENDS:
return Object.assign({}, state, {
friends: action.payload
});
default:
return initialState;
}
}
我希望侧面抽屉在“登录”和“地图”链接下打开并呈现抽屉中的用户列表
答案 0 :(得分:1)
userReducer
的默认情况是返回initialState
而不是state
,因此通过Redux存储的不是SET_FRIENDS
的每个操作(例如TOGGLE_SIDEDRAWER
)都会将userReducer
重置为initialState
的{{1}}到users
。相反,返回null
,您应该会很好。
state