【发布时间】:2017-03-30 20:50:08
【问题描述】:
我尝试向我的应用程序添加一个状态,该状态在某个事件过去时刚刚保存了一个布尔值。我无法弄清楚我在这里做错了什么。
减速机:
import * as actionTypes from '../constants/action-types.js';
const initialState = [{
eventPassed: false
}];
export default function eventPassed(state = initialState, action) {
switch (action.type) {
case actionTypes.EVENT_PASSED:
return true;
default:
return state;
}
}
行动:
import * as actionTypes from '../constants/action-types';
export function eventPassed(eventPassed) {
return {
type: actionTypes.EVENT_PASSED,
payload: { eventPassed: eventPassed }
};
}
组件周围的容器:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import Example from '../components/example.jsx';
import { eventPassed } from '../actions/app-actions';
class ExampleContainer extends Component {
render() {
return (
<Example {...this.props} />
);
}
}
const mapDispatchToProps = (dispatch) => ({
actions: bindActionCreators({
eventPassed
}, dispatch)
});
const mapStateToProps = (state) => ({
eventPassed: state.eventPassed
});
export default connect(mapStateToProps, mapDispatchToProps)(ExampleContainer);
组件:
import React, { Component, PropTypes } from 'react';
class Example extends Component {
constructor() {
super();
this.action = this.action.bind(this);
}
componentDidMount() {
this.props.actions.eventPassed(true);
}
action() {
console.log(this.props.eventPassed);
}
render() {
return (
<div>
<button onClick={this.action}>Action</button>
</div>
);
}
}
export default Example;
当我尝试在 <Example /> 组件中记录 “this.props.eventPassed” 时,它给了我“undefined”。有什么遗漏吗?这似乎是 redux 中最简单的 store 使用方法。
【问题讨论】:
-
你的 reducer 必须返回状态对象,在你的情况下是 {eventPassed: true}
-
<Example />组件上没有 this.props.eventPassed。请参阅下面的答案 -
编辑了我的答案以提高可读性
标签: javascript reactjs redux react-redux