React Redux Reducer已触发但未更改状态

时间:2018-03-01 18:23:11

标签: reactjs redux reducers

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

据我所知,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);

3 个答案:

答案 0 :(得分:1)

您的代码应该是这样的

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

答案 1 :(得分:1)

您正在检查props.user中的componentWillMount,其中没有显示您的更新。 而是检查render方法或componentWillReceiveProps等其他生命周期处理程序方法中的状态更改。

答案 2 :(得分:0)

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

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

请发布您的console.log(res.data),看看这是不是问题。

相关问题