Mapdispatchtoprops没有赋予道具功能

时间:2019-11-26 16:34:07

标签: javascript reactjs redux react-redux

import React, { Component } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import { ShelfModal } from "./shelf-modal";
import { openShelfModal } from "../../../redux/actions/shelf-modal";

export class ShelfTest extends Component {
  constructor(props) {
    super(props);
  }


  render() {
    const { openModal } = this.props;


    return (
      <div>
        <button onClick={openModal}>Open Shelf</button>

        <ShelfModal />
      </div>
    );
  }
}

export const mapDispatchToProps = dispatch => ({
         openModal: () => dispatch(openShelfModal())
       });

export const mapStateToProps = state => {
  return {
  };
};

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

上面是我正在使用的模式的代码。我试图在openModal内的mapDispatchToProps中的render中获得props函数,但它没有显示在props内部。这些操作是从正确的路径导入的。怎么了?

1 个答案:

答案 0 :(得分:0)

在通过mapStateToPropsmapDispatchToPropsShelfTest连同connect一起导出时,不需要同时导出mapDispatchToPropsimport React, { Component } from "react"; import PropTypes from "prop-types"; import { connect } from "react-redux"; import { ShelfModal } from "./shelf-modal"; import { openShelfModal } from "../../../redux/actions/shelf-modal"; class ShelfTest extends Component { constructor(props) { super(props); } render() { const { openModal } = this.props; return ( <div> <button onClick={openModal}>Open Shelf</button> <ShelfModal /> </div> ); } } const mapDispatchToProps = dispatch => { return { openModal(){ dispatch(openShelfModal()) } } }; const mapStateToProps = state => { return { }; }; export default connect( mapStateToProps, mapDispatchToProps )(ShelfTest);

我也很好地重组了您的openShelfModal

mapDispatchToProps

编辑

或者,您可以尝试在自己的connect语句中包括export default connect(mapStateToProps, {openShelfModal}) (ShelfTest); 。无需声明export class ShelfTest extends Component {,而是可以使用connect来构造导出。

connect

只要正确设置了中间件/路由,它就可以正常工作。

如果您要在底部使用{{1}}进行导出,则也不需要顶部的{{1}}。