javascript - 当我想使用外部“this”关键字时出现“_this is undefined”错误
问题描述
在以下示例中,我收到此错误
类型错误:_this 未定义
我尝试了很多方法,但找不到修复错误的方法,我该如何解决?
component_for_home_page.js
import { dispatch } from 'dispatch'
class Home extends PureComponent {
componentDidMount() {
dispatch('ADD_TEXT', 'Beep, Boop')
// instead of following
// this.props.dispatch({
// type: 'ADD_TEXT'
// text: 'Beep, Boop'
// })
//
}
render() {
return (<p>{this.props.text}</p>)
}
}
function mapStateToProps(state) {
return {
...state
}
}
const connectedHomeComponent = connect(mapStateToProps)(Home)
export {
connectedHomeComponent
}
简化调度.js
const dispatch = (type, text) => {
return this.props.dispatch({
type,
text
})
}
解决方案
在simplify_dispatch.js
中,您正在尝试访问this.props
,但这不是在正确的上下文中,因为您想this
来自您的component_for_home_page
. 我不确定你为什么不想只使用this.props.dispatch(...)
,但如果你坚持遵循这种方法,我建议将第三个参数传递给你的函数 in simplify_dispatch.js
,this.props
或者this.props.dispatch
simplify_dispatch.js
const dispatch = (type, text, passedDispatch) => {
return passedDispatch({
type,
text
})
}
component_for_home_page.js
...
componentDidMount() {
dispatch('ADD_TEXT', 'Beep, Boop', this.props.dispatch)
}
...
推荐阅读
- angular - 我可以运行几次 ng build 命令吗?
- jenkins - Jenkins:Nexus Repository Manager 2.x 连接成功,但显示 0 个托管版本 Maven 2 存储库
- ios - React Native App 在后台模式下退出
- javascript - 使用 JavaScript 导出带有表单输入值的 html 表
- user-interface - 在 Cloudera 中创建表单
- javascript - 未捕获的类型错误:尝试在 Vuejs 中调用 onchange() 方法时无法读取未定义的属性“应用”
- ansible - ansible 中是否有用于跨多个主机创建虚拟机的平衡概念?
- pipenv - pipenv`ModuleNotFoundError:没有名为“pip.basecommand”的模块
- android - 如何在android中设置视图的边框底部
- r - rmarkdown设置kable的位置