1

我正在处理登录身份验证。用户成功登录后,我想根据状态中的令牌值显示注销按钮。用户成功登录但实际上状态为空并且没有从快速服务器传递的值。因此,如果状态令牌属性为空,则登录后不会显示注销按钮。

接口代码

import axios from 'axios'

export default {
   user:{
       login:(credential) => axios.post('/api/auth',{credential}).then(res => res.data.user)
   }
}

动作代码

import {USER_LOGGED_IN} from '../types'
import api from '../api'

export const userLoggedIn = user => ({
    type: USER_LOGGED_IN,
    user
  });
export const login = (credential) =>(dispatch) => api.user.login(credential).then(user => dispatch(userLoggedIn(user)))

类型代码

export const USER_LOGGED_IN = 'USER_LOGGED_IN'

用户减速器

import { USER_LOGGED_IN } from "../types";

export default function user(state ={}, action = {}) {
  switch (action.type) {
    case USER_LOGGED_IN:
      return action.user;
    default:
      return state;
  }
}

根减速器

import { combineReducers } from "redux";

import user from "./reducers/user";
// import books from "./reducers/books";

export default combineReducers({
  user:()=>({

  })

});

主页

import React from 'react'
import {connect} from 'react-redux'
import PropTypes from 'prop-types'

import { Link } from  'react-router-dom'

 function HomePage({isAuthenticated}) {
  return (
    <div>
      <h1>Home Page</h1>
      { isAuthenticated ?    <button>Logout</button> : <Link to ="/login">Login</Link>}
    </div>
  )
}
HomePage.propTypes ={
  isAuthenticated:PropTypes.bool.isRequired
}
function mapStateToProps(state){
  console.log(state.user.token); // this shows undefined

  return{
    isAuthenticated:!!state.user.token
  }


}

export default connect(mapStateToProps)(HomePage)

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom'
import 'semantic-ui-css/semantic.min.css'
import {createStore,applyMiddleware} from 'redux'
import {Provider} from 'react-redux'
import thunk from 'redux-thunk'
import {composeWithDevTools} from  'redux-devtools-extension'
import App from './App';
import * as serviceWorker from './serviceWorker';
import rootReducer from './rootReducer'

const store = createStore(rootReducer,composeWithDevTools(applyMiddleware(thunk)))
ReactDOM.render(<BrowserRouter><Provider store={store}><App /></Provider></BrowserRouter>, document.getElementById('root'));
serviceWorker.unregister();
4

2 回答 2

1

将 rootreduer 文件更新为

import { combineReducers } from "redux";

import user from "./reducers/user";
// import books from "./reducers/books";

export default combineReducers({
  user
});
于 2019-11-09T06:16:55.027 回答
1

实际上你没有在组合减速器中提供你的用户减速器,你可以这样做

import { combineReducers } from "redux";

import user from "./reducers/user";

export default combineReducers({
 user
 })
});

希望能帮助到你

于 2019-11-09T06:25:32.973 回答