reactjs - 无法从 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。你能解释一下我在这里做错了什么吗?我将不胜感激任何帮助。
解决方案
你忘了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)
组件中的功能,该功能会分派一个动作。
推荐阅读
- java - JBOSS EAP 7.3:如何覆盖所有服务器或服务器组的 jboss.as.jpa.providerModule?
- django - 如何使用 Django 中的会话将所有表单数据从一个视图发送到另一个视图
- html - 为什么 Spartan 字体不垂直居中?
- django - 使用 Boto3 将 Django 表单上传到 AWS S3 会导致空文件
- php - 自动装配如何知道要通过什么类?
- java - 有没有将字符串中的整数转换为 JAVA 中的 ASCII 字符的解决方案?
- ios - 第二次实例化 ARSCNView 时崩溃
- mongodb - mongodb成员卡在startup2中
- python - 如何覆盖python脚本文件中的一些分配?
- javascript - 将内容写入新窗口