首页 > 解决方案 > 无法从 redux 的商店获取状态

问题描述

我正在开发 React/Redux 应用程序,并且在调度操作后从 redux 存储获取一个特定状态时遇到问题。我不知道为什么会这样,因为我在其他州没有遇到过这样的问题。这是我的代码:

减速器

import {SET_CURRENT_USER, SET_LECTURES} from '../actions/actionTypes';
import isEmpty from 'lodash/isEmpty';

const initialState = {
  isAuthenticated: false,
  user: {},
  lectures: []
}

export default (state = initialState, action = {}) => {
    switch(action.type) {
    case SET_CURRENT_USER:
        return {
            isAuthenticated: !isEmpty(action.user),
            user: action.user
        };
    case SET_LECTURES:
        return {
            lectures: action.lectures
          }
    default: return state;
    }
}

动作创建者和调度动作

import { SET_LECTURES } from './actionTypes';

export const setLectures = (lectures) => {
  return {
    type: SET_LECTURES,
    lectures
  }        
}
export const lecture = (lectures) => {
   return dispatch => {
    console.log(lectures);
    dispatch(setLectures(lectures));
  }
}

问题在于SET_LECTURES动作类型,特别lectures是动作对象的属性。在我想从中获取 state 的组件中lectures,我执行mapStateToProps以下操作:

const mapStateToProps = function(state) {
  return {
    notifications: state.notifications,
    lectures: state.lectures
  }
}
/*
*Code of the class
*/
export default connect(mapStateToProps, null)(AddQuestionForm);

我跳过了触发 dispatching action type 的代码SET_LECTURES,因为它工作正常。我还使用 React Developer Tools 来跟踪状态,并且有lectures状态。我只是无法从我的组件中获取此状态,当我执行console.log(this.props.lectures)from时ComponentDidMount(),它显示undefined。你能解释一下我在这里做错了什么吗?我将不胜感激任何帮助。

标签: reactjsredux

解决方案


你忘了dispatch

export const lectureAction = lectures => dispatch => {
   return dispatch => {
    dispatch(setLectures(lectures));
  }
}

在组件中:

import { bindActionCreators } from 'redux';

const mapStateToProps = function(state) {
  return {
    notifications: state.notifications
  }
}

// use map dispatch for actions:
const mapDispatchToProps = dispatch => 
    bindActionCreators({
        lectures: lectureAction
    }, dispatch);

/*
*Code of the class
*/

// connect map dispatch here:
export default connect(mapStateToProps, mapDispatchToProps)(AddQuestionForm);

现在您可以访问this.props.lectures(someParams)组件中的功能,该功能会分派一个动作。


推荐阅读