2

我正在尝试使用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)
4

3 回答 3

2

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

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

handleclick(){
  this.props.dispatch(...)
}
于 2017-09-01T07:17:55.397 回答
1

您需要将调度功能传递给您的道具:

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

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

this.props.showLoading();
...
this.props.hideLoading();
于 2017-09-01T07:17:08.510 回答
0

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

阅读有关 mapDispatchToProps 的更多信息。

于 2017-09-01T08:03:30.823 回答