Jim*_*ers 8 javascript reactjs redux react-redux
我试图在我的应用程序中添加一个状态,当一些事件通过时,它只保存了一个布尔值.我无法弄清楚我在这里做错了什么.
减速器:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
行动:
import * as actionTypes from '../constants/action-types';
export function eventPassed(eventPassed) {
return {
type: actionTypes.EVENT_PASSED,
payload: { eventPassed: eventPassed }
};
}
Run Code Online (Sandbox Code Playgroud)
组件周围的容器:
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);
Run Code Online (Sandbox Code Playgroud)
零件:
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;
Run Code Online (Sandbox Code Playgroud)
当我尝试在组件中记录"this.props.eventPassed"时,<Example />它给了我" undefined ".有什么遗失的吗?这似乎是redux中最简单的商店用途.
Pin*_*eda 12
为什么this.props.eventPassed记录为"undefined"?:
此时
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.结果是,当您登录此属性时,您会收到" undefined "
mapDispatchToProps 需要返回一个值
带有块体的箭头函数不会自动返回值,因此必须定义一个值.所以你的功能需要看起来像:
mapDispatchToProps = (dispatch) => {
return { actions: bindActionCreators(eventPassed, dispatch) }
}
Run Code Online (Sandbox Code Playgroud)
初始状态是包含对象的数组:
const initialState = [{
eventPassed: false
}];
Run Code Online (Sandbox Code Playgroud)
由于您以后尝试引用它object { eventPassed: true}而不是对象数组,[ { eventPassed: true } ]它应该是:
const initialState = {
eventPassed: false
};
Run Code Online (Sandbox Code Playgroud)
reducer需要传回正确的更新(但未突变)状态:
export default function eventPassed(state = initialState, action) {
switch (action.type) {
case actionTypes.EVENT_PASSED:
return {
...state,
eventPassed: action.payload
};
default:
return state;
}
}
Run Code Online (Sandbox Code Playgroud)
你最初做的是返回一个不再是一个对象的状态(或者在原始情况下是一个对象数组)但只是返回 true
| 归档时间: |
|
| 查看次数: |
23185 次 |
| 最近记录: |