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

问题描述 投票:0回答:3

我正在尝试使用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);
reactjs redux reducers
3个回答
1
投票

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


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

0
投票

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.