React Redux Reducer 触发但不改变状态

React Redux Reducer triggered but not changing state

我正在尝试使用 authenticated: true 和用户数据设置应用程序状态。 Reducer 被触发(我可以看到 console.log)但它正在返回初始状态(isAuthenticated:false,用户:{})

据我所知,Thunk 工作正常

我在组件中获取的道具是 {isAuthenticated: false, user{}}

我以前也做过类似的事情,所以我不确定为什么会这样

import { AUTHENTICATED } from '../actions/types'

const initialState = {
    isAuthenticated: false,
    user: {}
}

export default function(state = initialState, action) {
    switch (action.type) {
        case AUTHENTICATED:
            console.log(action.payload)
            return {
                ...state,
                isAuthenticated: true,
                user: action.payload.user
            }

        default:
            return state
    }
}

动作创作者user.js

import axios from 'axios';
import history from '../history';
import config from '../config'
import { AUTHENTICATED } from './types';

export function authUser(token){
   return function(dispatch){
      const data = {"token": token}
      axios.post(`${config.api_url}/authuser`, data)
         .then((res) => {
            dispatch({type: AUTHENTICATED, payload: res.data})
         })
         .catch((err) => console.log(err))
   }
}

组件dashboard.js

import React, { Component } from 'react';
import { connect } from 'react-redux';
import history from '../history';
import * as actions from '../actions/memberActions';

   class Dashboard extends Component {

      componentWillMount(){
            const token = window.localStorage.getItem('token');
               if(!token){
                  history.push('/')
               }else{
                  this.props.authUser(token);
                  console.log(this.props.user);
         }

      };
      render() {
         return (
            <div>
               <h2>This will be a dashboard page</h2>
               <p>There should be something here:{ this.props.authenticated }</p>
               <h1>OK</h1>

            </div>
         )
      }
   }

function mapStateToProps(state){
   return {
      user: state.user
   }

}

export default connect(mapStateToProps, actions)(Dashboard);

你的代码应该是这样的

export default function(state = initialState, action) {
    switch (action.type) {
        case AUTHENTICATED:
            console.log(action.payload)
            return state =  {
                ...state,
                isAuthenticated: true,
                user: action.payload.user
            }

        default:
            return state
    }
}

从外观上看,您的 res.data 对象似乎在 dispatch({type: AUTHENTICATED, payload: res.data}) 中没有 user 属性.

所以当你做 user: action.payload.user 时,你基本上是在说 user: undefined

请post你的console.log(res.data)看看是否是这个问题。

您正在检查 componentWillMount 中的 props.user,它没有显示您的更新。 相反,请检查您的 render 方法或另一个 life-cycle 处理程序方法(如 componentWillReceiveProps.

中的状态更改