为什么 "State" 在 action 发送后是空的?

Why "State" is empty after action is dispatched?

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

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

将 rootreduer 文件更新为

import { combineReducers } from "redux";

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

export default combineReducers({
  user
});

实际上你并没有在 combine reducers 中提供你的 user reducer,你可以这样做

import { combineReducers } from "redux";

import user from "./reducers/user";

export default combineReducers({
 user
 })
});

希望对您有所帮助