Reactjs 未使用react和redux在我的函数上定义分派
我试图在从API服务器获取数据的过程中显示加载条,我没有使用promise中间件,所以我决定不使用它,示例中说这样做Reactjs 未使用react和redux在我的函数上定义分派,reactjs,redux,redux-thunk,redux-middleware,Reactjs,Redux,Redux Thunk,Redux Middleware,我试图在从API服务器获取数据的过程中显示加载条,我没有使用promise中间件,所以我决定不使用它,示例中说这样做 import { showLoading, hideLoading } from 'react-redux-loading-bar' dispatch(showLoading()) // do long running stuff dispatch(hideLoading()) 它给了我这个 Uncaught ReferenceError: dispatch is not d
import { showLoading, hideLoading } from 'react-redux-loading-bar'
dispatch(showLoading())
// do long running stuff
dispatch(hideLoading())
它给了我这个
Uncaught ReferenceError: dispatch is not defined
我和其他图书馆有过类似的问题,那次我放弃了,这次我想真正了解它是如何工作的,所以任何信息都非常感谢。下面是导致错误的代码、speicifc函数和类名
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)
从“React”导入React
从“redux”导入{bindActionCreators}
从“react redux”导入{connect}
从“react-redux加载栏”导入{showLoading,hideLoading}
将*作为xxxxx操作从“../../actions/xxxxx”导入
类xxxxxx扩展了React.Component{
建造师(道具){
超级(道具)
this.handleclick=this.handleclick.bind(this)
}
handleclick(){
分派(showLoading())
asynchronousGetFunction(目标url,函数(数据){
分派(hideLoading())
})
}
render(){
returnyyyyyyyy
}
}
函数MapStateTops(状态){
返回{
}
}
功能映射DispatchToprops(调度,状态){
返回{
XXXXX操作:bindActionCreators(XXXXX操作,调度)
};
}
导出默认连接(
MapStateTops,
mapDispatchToProps
)(xxxxxx)
您需要将分派功能传递给您的道具:
function mapDispatchToProps(dispatch, state) {
return {
xxxxxActions: ....,
showLoading: function () {
dispatch(showLoading());
},
hideLoading: function () {
dispatch(hideLoading());
},
};
}
然后,在组件中使用它:
this.props.showLoading();
...
this.props.hideLoading();
一旦连接组件,
dispatch
将成为prop
。这同样适用于xxxxx操作
在这种情况下,句柄将是:
handleclick(){
this.props.dispatch(...)
}
您不需要在组件中使用“分派”。使用mapDispatchToProps中的dispatch绑定函数
阅读有关mapDispatchToProps的更多信息 当您使用bindActionCreators时,每个action creator都被包装到一个分派调用中,这样就可以使用道具直接调用它们。因此,在您的情况下,要分派,请使用类似这样的.props.xxxxx actions.yourActionToDispatch()看到这个问题,谢谢这似乎是可行的,但是遇到一些由于修复而无法预见的错误,我认为这不是因为这个答案中的错误,而是因为我的代码中的一些不相关的东西,顺便说一句,当我打电话给showLoading时,它破坏了商店中与xxxxActions相关的一切。我想我了解发生了什么,它们被作为xxxxActions事件发送,从而打击了我的减速机进行xxxxActions,它应该在哪里撞击减速器以进行react redux加载是的,我觉得我误解了调度的工作原理,谢谢你的提示