我尝试将状态添加到我的应用程序,只需保存一个布尔值,当一些事件已经过去了。我无法弄清楚我在做什么错。
减速器:
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;
当我尝试在组件中记录“ this.props.eventPassed”时,<Example />
它给了我“ undefined ”。缺少什么吗?这似乎是redux中存储最简单的用法。
为什么this.props.eventPassed被记录为“未定义”?:
动作功能(
eventPassed
)你想在这一点上,在访问中不存在this.props.actions.eventPassed
。它实际上只上存在this.props.actions
。这是因为您将action方法绑定到mapDispatchToProps中的值“ actions ”。依次提供了
eventPassed
通过提供访问操作的权限this.props.actions
。由于this.props.actions点
eventPassed
,以试图访问this.props.actions.eventPassed
你的行动尝试访问“eventPassed”的财产eventPassed
。其结果是,当你登录该物业收到“未定义”
mapDispatchToProps
需要返回一个值
一个箭头功能与块体不会自动返回一个值,因此必须进行定义。因此,您的函数需要如下所示:
mapDispatchToProps = (dispatch) => {
return { actions: bindActionCreators(eventPassed, dispatch) }
}
初始状态是一个包含对象的数组:
const initialState = [{
eventPassed: false
}];
由于您稍后尝试将其引用为an,object { eventPassed: true}
而不是对象数组,[ { eventPassed: true } ]
因此应为:
const initialState = {
eventPassed: false
};
减速机需要传回正确的更新(但未突变)状态:
export default function eventPassed(state = initialState, action) {
switch (action.type) {
case actionTypes.EVENT_PASSED:
return {
...state,
eventPassed: action.payload
};
default:
return state;
}
}
你最初做的是返回该不再是一个对象(或在原来的情况下对象的数组)的状态,但只是价值 true
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句