功能内部的访问调度

时间:2019-09-25 18:19:57

标签: reactjs redux react-redux

我希望下面的“ VerifyEmailResend”函数能够访问mapDispatchToProps内部的两个调度方法。我该怎么办?

VerifyEmailResend()已导出,因为我希望可以在整个应用程序中调用它。

此应用是使用Redux在React中编写的。

我知道通常使用connect方法,但是connect是专门用于React组件的。我想念这里有类似的东西吗?

import React, { Component, Fragment } from 'react'
import { api } from '../../api'
import { bool, func } from 'prop-types'
import VerifyEmailResent from './VerifyEmailResent'
import VerifyEmailVerified from './VerifyEmailVerified'
import { connect } from 'react-redux'

class VerifyEmail extends Component {
    static propTypes = {
        // has the verify email been resent \\
        verifyEmailResent: bool,
        // have you already verified your email \\
        verifyEmailVerified: bool,
        // set status of verify email \\
        onSetVerifyEmailResent: func.isRequired,
        // set status of the email verified \\
        onSetVerifyEmailVerified: func.isRequired
    }

    resent = () => {
        const { onSetVerifyEmailResent } = this.props
        onSetVerifyEmailResent(false)
    }

    verified = () => {
        const { onSetVerifyEmailVerified } = this.props
        onSetVerifyEmailVerified(false)
    }

    render() {
        const { verifyEmailResent, verifyEmailVerified } = this.props
        return (
            <Fragment>
                {verifyEmailResent && (
                    <VerifyEmailResent action={this.resent} />
                )}
                {verifyEmailVerified && (
                    <VerifyEmailVerified action={this.verified} />
                )}
            </Fragment>
        )
    }
}

const mapStateToProps = state => ({
    verifyEmailResent: state.eventListenerState.verifyEmailResent,
    verifyEmailVerified: state.eventListenerState.verifyEmailResent
})

const mapDispatchToProps = dispatch => ({
    onSetVerifyEmailResent: verifyEmailResent =>
        dispatch({ type: 'VERIFY_EMAIL_RESENT_SET', verifyEmailResent }),
    onSetVerifyEmailVerified: verifyEmailVerified =>
        dispatch({ type: 'VERIFY_EMAIL_RESENT_VERIFIED', verifyEmailVerified })
})

const VerifyEmailResend = () => () => {
    api.user.resendEmailVerification().then(data => {
        if (data.resent) {
            //onSetVerifyEmailResent(true)
        }
        if (data.verified) {
            //onSetVerifyEmailVerified(false)
        }
    })
}

export connect(null, mapDispatchToProps)(VerifyEmailResend)

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(VerifyEmail)

1 个答案:

答案 0 :(得分:1)

我不确定您对此感到困惑。但是您可以做到:

const VerifyEmailResend = () => {}
export default connect(null, mapDispatchToProps)(VerifyEmailResend)

根据您需要的命名导出,可以执行以下操作:

export {
  VerifyEmailResend: connect(null, mapDispatchToProps)(VerifyEmailResend)
}

您通常可以像这样导入它:

import { VerifyEmailResend } from '..'

根据您的评论,您可以根据需要将其命名为以下内​​容:

{ VerifyEmailResend() }

或类似:

<VerifyEmailResend />