成功登录后从redux商店显示用户信息

时间:2017-08-30 17:09:58

标签: reactjs redux react-redux

我有一些问题在我的react组件中显示更新的redux状态。基本上,我要做的是显示成功登录的用户信息,该信息通过登录操作发送到redux store。

以下是我的登录操作:

export function login(userDetails) {
return dispatch =>
axios.post(`${API_URL}/signin`, userDetails).then((res) => {
  const token = res.data.Token;
  localStorage.setItem('token', token);
  setAuthorizationToken(token);
  const decoded = jwt.decode(res.data.Token);
  dispatch({
    type: SET_CURRENT_USER,
    user: decoded.currentUser
    });
  });
}

成功登录的用户将被重定向到仪表板组件:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import HeaderSideBar from '../includes/header-side-bar';

class Dashboard extends Component{

render(){

     const {username} = this.props.user;

    return (
        <HeaderSideBar username={username}/>
    )
 }
}

function mapStateToProps(state) {
return {
    user: state.user
    }
}
export default connect(mapStateToProps)(Dashboard)

我的减速机:

    import { AUTH_USER,
  UNAUTH_USER,
  AUTH_ERROR,
  USER_EXIST,
 SET_CURRENT_USER
} from '../actions/types';

const INITIAL_STATE = { userExist: '', error: '', message: '', user: '', 
content: '', authenticated: false };

function authReducer(state = INITIAL_STATE, action) {
  switch (action.type) {
case AUTH_USER:
  return { ...state, error: '', message: 'Successfully registered', 
authenticated: true };
case UNAUTH_USER:
  return { ...state, authenticated: false };
case AUTH_ERROR:
  return { ...state, error: action.payload };
case USER_EXIST:
  return { ...state, error: action.error };
case SET_CURRENT_USER:
  console.log(action.user);
  return { ...state, user: action.user };
default:
  return state;
  }
}

export default authReducer;

我想在用户仪表板中显示更新状态的值。例如用户名,全名

1 个答案:

答案 0 :(得分:0)

尝试直接使用仪表板组件中的道具,例如

render(){ return ( <HeaderSideBar username={this.props.user}/> ) }