为什么派遣行动后“状态”为空?

时间:2019-11-09 04:45:33

标签: reactjs react-redux reducers thunk

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

API代码

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;
  }
}

rootReducer

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();

2 个答案:

答案 0 :(得分:1)

将rootreduer文件更新为

import { combineReducers } from "redux";

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

export default combineReducers({
  user
});

答案 1 :(得分:1)

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

import { combineReducers } from "redux";

import user from "./reducers/user";

export default combineReducers({
 user
 })
});

希望有帮助