反应高阶组件语法

时间:2019-05-07 23:05:50

标签: reactjs redux redux-form recompose

概述

在将反应组件与高阶组件包装在一起以访问道具时,我很难理解在网上找到的语法。

下面的示例(有效)是将组件包装

withFireStore => ReduxForms => Connect => Component

export default withFirestore(
    reduxForm({
        form: "createStudents", validate
    })(connect(
          mapStateToProps,
          mapDispatchToProps)(CreateStudentsForm))
);

我要做什么的背景

最终,我试图通过作为revalidate.js库一部分使用的Validate函数访问道具。遵循解决方案from this stackoverflow post时,我没有从props映射到状态的props。我相信这是由于我如何订购我的高阶组件。

问题

我实际上需要由连接包裹的ReduxForm,以便它可以访问我从redux状态映射的道具。

withFireStore => Connect => ReduxForms => Component

  尝试1
export default withFirestore(
    (connect(
            mapStateToProps,
            mapDispatchToProps
        )
        (reduxForm({
            form: "createStudents", validate
        }))
        (CreateStudentsForm)
    )
);
错误

Cannot call a class as a function

我以为我把括号放在错误的位置,但是当我像这样移动它们时,我就得到了

  尝试#2
export default withFirestore(
    (connect(
            mapStateToProps,
            mapDispatchToProps
        )
        (reduxForm({
            form: "createStudents", validate
        })
        (CreateStudentsForm))
    )
);
错误

Uncaught Invariant Violation: You must pass a component to the function returned by connect.

问题

  1. 我发现这样的链接功能非常混乱,是否有更好的编写方法?
  2. 如何编写此代码,以便reduxFrom将由connect包裹,这应该使我可以访问表单中的道具。

添加到问题:

CreateStudentForm.js导入

import React, { Component } from "react";
import { reduxForm, Field } from "redux-form";
import {compose} from 'redux';
import { Container, Form, Col, Button } from "react-bootstrap";
import MaterialIcon from '../../material-icon/materialIcon';
import { withFirestore } from "react-redux-firebase";
import { connect } from "react-redux";
import TextInput from "../../forms/textInput";
import { combineValidators, isRequired } from "revalidate";
import { setupStudentForm } from '../../../store/actions/students';

CreateStudentForm导入到一个名为modal.js的有状态组件中

Modal.js导入

import React, { Component } from "react";
import { connect } from "react-redux";
import { Modal, Button, Row, Col } from "react-bootstrap";
import Aux from '../../hoc/Aux';
import CreateClassForm from "../createClass/createClassForm";
import EditClassForm from "../editClass/editClassForm";
import EditHomeworkForm from "../editHomework/editHomeworkForm";
import CreateHomeworkForm from "../createHomework/createHomeworkForm";
import CreateStudentsForm  from "../createStudents/createStudentsForm";
import { withFirestore } from "react-redux-firebase";

1 个答案:

答案 0 :(得分:1)

尝试compose,例如:

export default compose(
  withFirestore, 
  reduxForm({
    form: "createStudents", validate
  }),
  connect(
    mapStateToProps,
    mapDispatchToProps
  )
)(CreateStudentsForm);