小编典典

为什么在使用redux和react.js时我的道具为undefined?

reactjs

我试图向我的应用程序添加一个状态,该状态仅在某些事件过去后才保存一个布尔值。我无法弄清楚我在做什么错。

减速器:

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中存储最简单的用法。


阅读 472

收藏
2020-07-22

共1个答案

小编典典

为什么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您正在尝试访问action上的’eventPassed’属性eventPassed。结果是,当您登录此属性时,您会收到“
undefined


其他必要的修正:

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

2020-07-22