REDUX-REACT-调度未定义

时间:2019-05-25 20:19:58

标签: reactjs redux jsx

组件中的调度是未定义的,而mapDispatchToProps中的调度是可以的

动作和减速器没问题-100%; 我想转移到行动中,以创建请求并从行动中运行行动

我的组件

import React, { Component, Fragment } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import styled from 'styled-components';
import  { carAction, fetchDogAction } from '../../../actions/CarAction';

class CarListContainer extends Component {
    render () {

        const { cars, carAction, dispatch, dog } = this.props;

        console.log(dispatch) // THIS UNDEFINED!!!!

        return(
            <Fragment>
                <Title onClick={() => {
                    fetchDogAction(dispatch)
                }}>HEllo</Title>

                {cars.map((elem) => 
                    <Title onClick={() => {carAction (elem)}} key={elem.id}>{elem.mark}</Title>
                )}

                {dog ? <img src={dog.message} /> : null }
            </Fragment>
        )
    }
}

const Title = styled('h2')`
    color: red;
    font-size: 30px;
`;

function mapStateToProps (state) {
    return {
        cars: state.cars,
        dog: state.dog
    }
}

function mapDispatchToProps(dispatch) {
    console.log(dispatch) //THIS DISPATCH IS OK
    return bindActionCreators ({
        carAction: carAction,
        fetchDogAction: fetchDogAction
    }, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(CarListContainer);

1 个答案:

答案 0 :(得分:1)

由于mapDispatchToProps内部使用bindActionCreators,因此不建议您这样做,这是由于不建议在mapDispatchToProps()中使用bindActionCreators()。

bindActionCreators and mapDispatchToProps - Do I need them?

您可以尝试使用箭头函数并直接在mapDispatchToProps方法中调度动作。

import * ACTIONS from './actions'

function mapDispatchToProps(dispatch) {
    return {
        carAction: (elem) => dispatch(ACTIONS.fetchCarAction(elem)) ,
        dogAction: () => dispatch(ACTIONS.fetchDogAction()) 
    }
}

//action creators import them into your component
export const fetchCarAction = (elem) => {
  return {
    type: ACTION_TYPES.CARACTION,
    payload: elem
  }
}

export const fetchDogAction = () => {
  return {
    type: ACTION_TYPES.DOGACTION,
  }
}

//render method

<Title onClick={() => this.props.dogAction() }>HEllo</Title>


{cars.map((elem) => 
  <Title onClick={() => this.props.carAction(elem) } key={elem.id}>{elem.mark} 
  </Title>
  )}

因此,在渲染中,您将在mapDispatchToProps中调用属性的名称,而不是动作创建者的名称,我将动作创建者的名称和属性的名称保持不同,以便您可以看到。

如果您想要一个功能齐全的react-redux应用程序,可以查看我构建的这个入门项目,我对此有很好的反馈。

https://github.com/iqbal125/modern-react-app-sample