【问题标题】:dispatch is not defined on my functions using react and redux没有使用 react 和 redux 在我的函数上定义调度
【发布时间】:2018-02-10 05:01:58
【问题描述】:

我正在尝试使用react-redux-loading-bar 在从 API 服务器获取数据期间显示加载栏,我不使用 promise 中间件,所以我决定不使用它,示例说明这样做

import { showLoading, hideLoading } from 'react-redux-loading-bar'

dispatch(showLoading())
// do long running stuff
dispatch(hideLoading())

它给了我这个。

Uncaught ReferenceError: dispatch is not defined

我与其他库有类似的问题并放弃了那个时间,这次我想真正了解它是如何工作的,因此非常感谢任何信息。下面是导致错误的代码,删除了特定的函数和类名。

import React from 'react'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'

import { showLoading, hideLoading } from 'react-redux-loading-bar'


import * as xxxxxActions from '../../actions/xxxxx'


class xxxxxx extends React.Component {

    constructor(props) {
        super(props)

        this.handleclick = this.handleclick.bind(this)
    }

    handleclick(){
        dispatch(showLoading())
        asynchronousGetFunction( target_url, function (data) {
            dispatch(hideLoading())
        })
    }

    render() {

        return  <li onClick={this.handleclick}>yyyyyyy</li>
    }
}

function mapStateToProps( state ){
    return {
    }
}

function mapDispatchToProps(dispatch, state) {

    return {
        xxxxxActions: bindActionCreators( xxxxxActions, dispatch )
    };
}

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(xxxxxx)

【问题讨论】:

  • 当您使用 bindActionCreators 时,每个动作创建者都被包装到一个调度调用中,因此可以使用道具直接调用它们。因此,在您的情况下,要调度,请使用类似 this.props.xxxxxActions.yourActionToDispatch()

标签: reactjs redux redux-thunk redux-middleware


【解决方案1】:

您不需要在组件中使用“调度”。将您的函数与 mapDispatchToProps 中的调度绑定。

阅读有关 mapDispatchToProps 的更多信息。

【讨论】:

  • 是的,我觉得我误解了调度的工作原理,感谢您的提示
【解决方案2】:

一旦你connect 你的组件,dispatch 就变成了prop。这同样适用于xxxxxActions...

在这种情况下,句柄将是:

handleclick(){
  this.props.dispatch(...)
}

【讨论】:

    【解决方案3】:

    你需要将 dispatch 函数传递给你的 props:

    function mapDispatchToProps(dispatch, state) {
        return { 
            xxxxxActions: ....,
            showLoading: function () {
                dispatch(showLoading());
            },
            hideLoading: function () {
                dispatch(hideLoading());
            },
        };
    }
    

    然后,在你的组件中使用它:

    this.props.showLoading();
    ...
    this.props.hideLoading();
    

    【讨论】:

    • 谢谢,这似乎有效,但是由于修复而遇到一些无法预料的错误,我认为这不是因为此答案中的错误,而是我的代码中不相关的内容,将尽快将其标记为答案我深入了解它。
    • 顺便说一句,当我调用 showLoading 时,它会炸毁与 xxxxActions 相关的商店中的所有内容
    • 我想我明白发生了什么,它们作为 xxxxActions 事件被分派,因此为 xxxxActions 命中了我的减速器,它应该为 react-redux-loading-bar 命中减速器
    猜你喜欢
    • 1970-01-01
    • 2019-10-11
    • 2017-08-28
    • 2017-08-09
    • 2019-01-10
    • 2021-02-23
    • 1970-01-01
    • 2020-08-18
    • 1970-01-01
    相关资源
    最近更新 更多